<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<!-- Copyright 1997 The Open Group, All Rights Reserved -->
<title>Shell Command Language</title>
</head><body bgcolor=white>
<center>
<font size=2>
The Single UNIX &reg; Specification, Version 2<br>
Copyright &copy; 1997 The Open Group

</font></center>
<hr size=2 noshade><blockquote>
<center>
<h2><a name = "tag_001">&nbsp;</a>Shell Command Language</h2>
</center>
<xref type="1" name="shell"></xref>
This chapter contains the definition of the
XSI Shell Command Language. 
See the <a href ="shellix.html">Shell Command Language Index</a> for
an overview.
<h3><a name = "tag_001_001">&nbsp;</a>Shell Introduction</h3>
The shell is a command language interpreter.
This chapter describes the syntax of that
command language as it is used by the
<i><a href="sh.html">sh</a></i>
utility and the
<i><a href="../xsh/system.html">system()</a></i>
and
<i><a href="../xsh/popen.html">popen()</a></i>
functions in the <b>XSH</b> specification.
<p>
The shell operates according to the following general overview
of operations.
The specific details are included in the cited sections
of this chapter.
<ol>
<p>
<li>
The shell reads its input from a file (see
<i><a href="sh.html">sh</a></i>),
from the
<b>-c</b>
option
or from the
<i><a href="../xsh/system.html">system()</a></i>
and
<i><a href="../xsh/popen.html">popen()</a></i>
functions in the <b>XSH</b> specification.
If the first line
of a file of shell commands starts with the characters
#!,
the results
are unspecified.
<p>
The construct
#!
is reserved for implementations wishing
to provide that extension.
A portable application cannot use
#!
as the first line of a shell script;
it might not be interpreted as a comment.
<p>
<li>
The shell breaks the input into tokens:
words and operators.
(See
<xref href=token><a href="#tag_001_003">
Token Recognition
</a></xref>.)
<p>
<li>
The shell parses the input into simple commands
(see
<xref href=simpcmd><a href="#tag_001_009_001">
Simple Commands
</a></xref>)
and compound commands
(see
<xref href=compcmd><a href="#tag_001_009_004">
Compound Commands
</a></xref>).
<p>
<li>
The shell performs various expansions
(separately) on different parts of each command, resulting in a
list of pathnames and fields to be treated as a command
and arguments (see
<xref href=wordexp><a href="#tag_001_006">
Word Expansions
</a></xref>).
<p>
<li>
The shell performs redirection (see
<xref href=redir><a href="#tag_001_007">
Redirection
</a></xref>)
and removes redirection operators and their operands from the
parameter list.
<p>
<li>
The shell executes a function (see
<xref href=funccmd><a href="#tag_001_009_005">
Function Definition Command
</a></xref>),
built-in (see
<xref href=sbi><a href="#tag_001_014">
Special Built-in Utilities
</a></xref>),
executable file or script, giving the
names of the arguments as positional
parameters numbered 1 to
<i>n</i>,
and the
name of the command (or in the case of
a function within a script, the name
of the script) as the positional
parameter numbered 0 (see
<xref href=cmdsea><a href="#tag_001_009_001_001">
Command Search and Execution
</a></xref>).
<p>
<li>
The shell optionally waits for the command to
complete and collects the exit status (see
<xref href=existat><a href="#tag_001_008_002">
Exit Status for Commands
</a></xref>).
<p>
</ol>
<hr size=2 noshade>
<h3><a name = "tag_001_002">&nbsp;</a>Quoting</h3>
<xref type="2" name="quoting"></xref>
Quoting is used to remove the special meaning of certain
characters or words to the shell.
Quoting can be used to preserve
the literal meaning of
the special characters in the next paragraph; prevent reserved
words from being recognised as such; and prevent parameter expansion
and command substitution within here-document processing (see
<xref href=heredoc><a href="#tag_001_007_004">
Here-document
</a></xref>).
<p>
The following characters must be quoted if they are to
represent themselves:
<pre>
<code>
|  &amp;  ;  &lt;  &gt;  (  )  $  `  \  "  '  &lt;space&gt;  &lt;tab&gt;  &lt;newline&gt;
</code>
</pre>
and the following may need to be quoted under certain circumstances.
That is, these characters may be special depending on
conditions described elsewhere in this specification:
<pre>
<code>
*   ?   [   #   ~   =   %
</code>
</pre>
<p>
The various quoting mechanisms are the escape character,
single-quotes and double-quotes.
The here-document represents another form of quoting; see
<xref href=heredoc><a href="#tag_001_007_004">
Here-document
</a></xref>.
<h4><a name = "tag_001_002_001">&nbsp;</a>Escape Character (Backslash)</h4>
<xref type="3" name="esc"></xref>
A backslash that is not quoted
preserves the literal value of the following character,
with the exception of a
newline character.
If a
newline character
follows the
backslash,
the shell will interpret this as line continuation.
The backslash and
newline characters
will be removed before splitting the input into tokens.
Since the escaped
newline character
is removed entirely from the input
and is not replaced by any white space,
it cannot serve as a token separator.
<h4><a name = "tag_001_002_002">&nbsp;</a>Single-quotes</h4>
Enclosing characters in single-quotes
(' ')
preserves the literal value of each character within the single-quotes.
A single-quote cannot occur within
single-quotes.
<p>
A backslash cannot be used to escape a single-quote
in a single-quoted string.
An embedded
quote can be created by writing, for example:
'a'\&quot;b',
which yields
a'b.
(See
<xref href=fldspl><a href="#tag_001_006_005">
Field Splitting
</a></xref>
for a better understanding of how portions of words are either
split into fields or remain concatenated.)
A single token can be made up
of concatenated partial strings containing
all three kinds of quoting or escaping,
thus permitting any combination of characters.
<h4><a name = "tag_001_002_003">&nbsp;</a>Double-quotes</h4>
<xref type="3" name="dquote"></xref>
Enclosing characters in double-quotes
(<b>" "</b>)
preserves the literal value of all characters within the double-quotes,
with the exception of the characters
dollar-sign, backquote and backslash, as follows:
<dl compact>

<dt>$<dd>The dollar-sign retains its special meaning introducing
parameter expansion (see
<xref href=parmexp><a href="#tag_001_006_002">
Parameter Expansion
</a></xref>),
a form of command substitution (see
<xref href=cmdsub><a href="#tag_001_006_003">
Command Substitution
</a></xref>),
and arithmetic expansion (see
<xref href=aritexp><a href="#tag_001_006_004">
Arithmetic Expansion
</a></xref>).

The input characters within the quoted string that are also enclosed
between "$(" and the matching "("
will not be affected by the
double-quotes, but rather
define that command whose output replaces the
$(...)
when the word is expanded.
The tokenising rules in
<xref href=token><a href="#tag_001_003">
Token Recognition
</a></xref>
are applied recursively to find the matching ")".

Within the string of characters from an enclosed
${
to the matching
"}",
an even number of
unescaped double-quotes or single-quotes, if any, must occur.
A preceding backslash character must be used to escape a literal
"{"
or
"}".
The rule in
<xref href=parmexp><a href="#tag_001_006_002">
Parameter Expansion
</a></xref>
will be used to determine the matching
"}".

<dt>`<dd>The backquote retains its special meaning introducing
the other form of command substitution (see
<xref href=cmdsub><a href="#tag_001_006_003">
Command Substitution
</a></xref>).
The portion of the quoted string from the initial backquote
and the characters up to the next backquote
that is not preceded by a backslash,
having escape characters removed,
defines that command whose output replaces `...`
when the word is expanded.
Either of the following cases produces undefined results:
<ul>

<li>
a single- or double-quoted string that begins, but does not end, within
the `...` sequence

<li>
a `...` sequence that begins, but does not end, within the
same double-quoted string.

</ul>

<dt>\<dd>The backslash retains its special meaning as an escape character (see
<xref href=esc><a href="#tag_001_002_001">
Escape Character (Backslash)
</a></xref>)
only when followed by one of the characters:
<pre>
<code>
$   `   "   \   &lt;newline&gt;
</code>
</pre>

</dl>
<p>
A double-quote must be preceded by a backslash
to be included within double-quotes.
The parameter @ has special meaning inside double-quotes
and is described in
<xref href=specpar><a href="#tag_001_005_002">
Special Parameters
</a></xref>.
<p>
In double-quoting, if a backslash is
immediately followed by a character that would be interpreted as having a
special meaning, the backslash is deleted and
the subsequent character is taken literally.
If a backslash does not precede a character that would
have a special meaning, it is left in place unmodified and the character
immediately following it is also left unmodified.
Thus, for example:
<pre>
<code>
"\$"  -&gt;  $

"\a"  -&gt;  \a
</code>
</pre>
The requirement that double-quotes be matched inside
${...}
within double-quotes and the rule for finding the matching
"}"
in
<xref href=parmexp><a href="#tag_001_006_002">
Parameter Expansion
</a></xref>
eliminate several
subtle inconsistencies in expansion for historical shells in rare cases;
for example:
<pre>
<code>
"${foo-bar"}
</code>
</pre>
yields
<b>bar</b>
when
<b>foo</b>
is not defined, and is an invalid substitution when
<b>foo</b>
is defined, in many historical shells.
The differences in processing the
${...}
form have led to inconsistencies between
historical systems.
A consequence of this rule is that single-quotes
cannot be used to quote the
"}"
within
${...};
for example:
<pre>
<code>
unset bar
foo="${bar-'}'}"
</code>
</pre>
is invalid because the
${...}
substitution contains an unpaired unescaped single-quote.
The backslash can be used to escape the
"}"
in this example to achieve the desired result:
<pre>
<code>
unset bar
foo="${bar-\}}"
</code>
</pre>
<p>
Some systems have allowed the end of the word to terminate
the backquoted command substitution, such as in:
<pre>
<code>
"`echo&nbsp;hello"
</code>
</pre>
<p>
This usage is undefined; the matching
backquote is required by this specification.
The other undefined usage can be illustrated by the example:
<pre>
<code>
sh -c '` echo "foo`'
</code>
</pre>
The description of the recursive actions involving command substitution
can be illustrated with an example.
Upon recognising the introduction of command substitution, the
shell must parse input (in a new context), gathering the
source for the command substitution until an unbalanced ")"
or ` is located.
For example, in the following:
<pre>
<code>
echo "$(date; echo "
        one" )"
</code>
</pre>
the double-quote following the
<i><a href="echo.html">echo</a></i>
does not terminate the first double-quote;
it is part of the command substitution script.
Similarly, in:
<pre>
<code>
echo "$(echo *)"
</code>
</pre>
the asterisk is not quoted since it is inside command
substitution; however:
<pre>
<code>
echo "$(echo "*")"
</code>
</pre>
is quoted (and represents the asterisk character itself).
<hr size=2 noshade>
<h3><a name = "tag_001_003">&nbsp;</a>Token Recognition</h3>
<xref type="2" name="token"></xref>
The shell reads its input in terms of lines from a file, from a
terminal in the case of an interactive shell
or from a string in the case of
<i><a href="sh.html">sh</a></i>
<b>-c</b>
or
<i><a href="../xsh/system.html">system()</a></i>.
The input lines can be of unlimited length.
These lines are parsed using two major modes:
ordinary token recognition
and processing of here-documents.
<p>
When an
<b>io_here</b>
token has been recognised by the grammar
(see
<xref href=shgram><a href="#tag_001_010">
Shell Grammar
</a></xref>),
one or more of the
subsequent lines immediately following the next
<b>NEWLINE</b>
token
form the body of one or more here-documents
and are parsed according to the rules of
<xref href=heredoc><a href="#tag_001_007_004">
Here-document
</a></xref>.
<p>
When it is not processing an
<b>io_here</b>,
the shell will break its input into tokens by applying the first applicable
rule below to the next character in its input.
The token will be from the
current position in the input until a token is delimited according to
one of the rules below; the characters forming the token are exactly those
in the input, including any quoting characters.
If it is indicated that a token is delimited, and
no characters have been included in a token, processing will continue
until an actual token is delimited.
<ol>
<p>
<li>
If the end of input is recognised, the current token will be delimited.
If there is no current token, the end-of-input indicator will be returned
as the token.
<p>
<li>
If the previous character was used as part of an operator and
the current character is not quoted and can be used
with the current characters to form an
operator, it will be used as part of that (operator) token.
<p>
Note that certain combinations of characters are invalid
in portable scripts, as shown in the grammar, and that some
systems have assigned these combinations (such as
|&amp;)
as valid control operators.
Portable scripts cannot rely on receiving errors
in all cases where this specification indicates that a syntax is invalid.
<p>
<li>
If the previous character was used as part of an operator and
the current character cannot be used
with the current characters to form an
operator, the operator containing the previous character will be delimited.
<p>
<li>
If the current character is backslash, single-quote
or double-quote
(\,
'
or
")
and it is not quoted, it
will affect quoting for subsequent characters
up to the end of the quoted text.
The rules for quoting are as described in
<xref href=quoting><a href="#tag_001_002">
Quoting
</a></xref>.
During token recognition no substitutions
will be actually performed, and the result token will contain exactly the
characters that appear in the input
(except for
newline character
joining), unmodified, including any
embedded or enclosing quotes or substitution operators, between the
quote mark and the end of the
quoted text.
The token will not be delimited by the end of the quoted field.
<p>
<li>
If the current character is an unquoted "$"
or `, the shell will identify the start of any candidates
for parameter expansion,
command substitution,
or arithmetic expansion
from their introductory unquoted character sequences: "$"
or
${,
$(
or `, and
$((,
respectively.
The shell will read sufficient input to determine the
end of the unit to be expanded (as explained in the cited sections).
While processing the characters, if instances of expansions or
quoting are found nested within the substitution, the shell
will recursively process them in the manner specified for the construct
that is found.
The characters found from the beginning of the
substitution to its end, allowing for any recursion necessary to
recognise embedded constructs, will be included unmodified in the
result token, including any embedded or enclosing substitution
operators or quotes.
The token will not be delimited by the end of the substitution.
<p>
<li>
If the current character is not quoted and can be used as the
first character of a new operator,
the current token (if any) will be delimited.
The current character will be used as the beginning of the next
(operator) token.
<p>
<li>
If the current character is an unquoted
newline character,
the current token will be delimited.
<p>
<li>
If the current character is an unquoted
blank character,
any token containing the previous character is delimited and the
current character will be discarded.
<p>
<li>
If the previous character was part of a word, the current
character will be appended to that word.
<p>
<li>
If the current character is a
"#",
it and all subsequent
characters up to, but excluding, the next
newline character
will be discarded as a comment.
The
newline character
that ends the line is not considered
part of the comment.
The
"#"
starts a comment only when it is at the beginning of a token.
Since the search for
the end-of-comment does not consider an escaped
newline character
specially, a comment cannot be continued
to the next line.
<p>
<li>
The current character will be used as the start of a new word.
<p>
</ol>
<p>
Once a token is delimited, it will be categorised
as required by the grammar in
<xref href=shgram><a href="#tag_001_010">
Shell Grammar
</a></xref>.
<h4><a name = "tag_001_003_001">&nbsp;</a>Alias Substitution</h4>
<xref type="3" name="alsub"></xref>
The processing of aliases is supported on all XSI-conformant systems.
<p>
After a token has been delimited,
but before applying the grammatical rules in
<xref href=shgram><a href="#tag_001_010">
Shell Grammar
</a></xref>,
a resulting word
that is identified to be the command name word of a simple command
is examined to determine if it is an unquoted, valid alias name.
However, reserved words in correct grammatical context
are not candidates for alias substitution.
A valid alias name (see the term
alias name
in
the <b>XBD</b> specification, <a href="../xbd/glossary.html"><b>Glossary</b>&nbsp;</a> )
is one that has been defined by the
<i><a href="alias.html">alias</a></i>
utility
and not subsequently undefined using
<i><a href="unalias.html">unalias</a></i>.
Implementations also may provide predefined valid aliases
that are in effect when the shell is invoked.
To prevent infinite loops in recursive aliasing,
if the shell is not currently processing an alias of the same name,
the word will be replaced by the value of the alias;
otherwise, it will not be replaced.
<p>
If the value of the alias replacing the word ends in a
blank character,
the shell will check the next command word for alias substitution;
this process continues until a word is found that is not
a valid alias or an alias value does not end in a
blank character.
<p>
When used as specified by this specification,
alias definitions will not be inherited by separate invocations of the shell
or by the utility execution environments invoked by the shell; see
<xref href=shexenv><a href="#tag_001_012">
Shell Execution Environment
</a></xref>.
<p>
The definition of
<i>alias name</i>
precludes an alias name containing a slash character.
Since the text applies to the command words of simple
commands, reserved words (in their proper places)
cannot be confused with aliases.
<p>
An example concerning trailing
blank characters
and reserved words follows.
If the user types:
<pre>
<code>
<b>$</b> alias foo="/bin/ls "
<b>$</b> alias while="/"
</code>
</pre>
<p>
The effect of executing:
<pre>
<code>
<b>$</b> while true
<b>&gt;</b> do
<b>&gt;</b> echo "Hello, World"
<b>&gt;</b> done
</code>
</pre>
is a never-ending sequence of
<b>Hello,&nbsp;World</b>
strings to the screen.
However, if the user types:
<pre>
<code>
<b>$</b> foo while
</code>
</pre>
the result will be an
<i><a href="ls.html">ls</a></i>
listing of <b>/</b>.
Since the alias substitution for
<b>foo</b>
ends in a space character,
the next word is checked for alias substitution.
The next word,
<b>while</b>,
has also been aliased, so it is substituted as well.
Since it is not in the proper position as a command
word, it is not recognised as a reserved word.
<p>
If the user types:
<pre>
<code>
<b>$</b> foo; while
</code>
</pre>
<b>while</b>
retains its normal reserved-word properties.
<hr size=2 noshade>
<h3><a name = "tag_001_004">&nbsp;</a>Reserved Words</h3>
Reserved words are words that have special meaning to the shell.
(See
<xref href=shcmds><a href="#tag_001_009">
Shell Commands
</a></xref>.)
The following words will be recognised as reserved words:
<pre>
<dl compact><dt> <dd>
<table <tr valign=top><td align=left>!
<td align=left>elif
<td align=left>fi
<td align=left>in
<td align=left>while
<tr valign=top><td align=left>case
<td align=left>else
<td align=left>for
<td align=left>then
<td align=left>{*
<tr valign=top><td align=left>do
<td align=left>esac
<td align=left>if
<td align=left>until
<td align=left>}
<tr valign=top><td align=left>done
</table>
</dl>
</pre>
<font size=2>
(*) In some historical systems, the curly braces
are treated as control operators.
To assist in future standardisation activities,
portable applications should avoid using unquoted
braces to represent the characters themselves.
It is possible that a future version of the ISO/IEC 9945-2:1993 standard
may require that { and }
be treated individually as control operators,
although the token {}
will probably be a special-case exemption
from this because of the often-used <i>find</i>{}
construct.
</font>
<p>
This recognition will occur only
when none of the characters are quoted and when the word is used
as:
<ul>
<p>
<li>
the first word of a command
<p>
<li>
the first word following one of the reserved words other than
<b>case</b>,
<b>for</b>,
or
<b>in</b>
<p>
<li>
the third word in a
<b>case</b>
or
<b>for</b>
command (only
<b>in</b>
is valid in this case).
<p>
</ul>
<p>
See the grammar in
<xref href=shgram><a href="#tag_001_010">
Shell Grammar
</a></xref>.
<p>
The following words may be recognised as reserved words
on some systems (when none of the characters are quoted),
causing unspecified results:
<pre>
<dl compact><dt> <dd>
<table <tr valign=top><th align=left>function
<th align=left>select
<th align=left>[[
<th align=left>]]
</table>
</dl>
</pre>
<p>
This list of unspecified reserved words is from the KornShell,
so portable applications cannot use them in places a reserved
word would be recognised without quoting some or all of
their characters.
<p>
Words that are the concatenation of a name and a colon
(:)
are reserved;
their use produces unspecified results.
This reservation
is to allow future implementations that support named
labels for flow control.
<p>
Reserved words are recognised only when they are delimited (that is,
meet the definition of
<b>word</b>
in the <b>XSH</b> specification),
whereas operators are themselves delimiters.
For instance,
"("
and ")"
are control operators, so that no
space character
is needed in
(list).
However,
"{"
and
"}"
are reserved words in
{&nbsp;list;},
so that in this case the leading
space character
and semicolon are required.
<hr size=2 noshade>
<h3><a name = "tag_001_005">&nbsp;</a>Parameters and Variables</h3>
<xref type="2" name="parms"></xref>
A parameter can be denoted by a name,
a number or one of the special characters
listed in
<xref href=specpar><a href="#tag_001_005_002">
Special Parameters
</a></xref>.
A variable is a parameter denoted by a name.
<p>
A parameter is set if it has an assigned value
(null is a valid value).
Once a variable is set, it can only be unset by using the
<i><a href="chap2.html#tag_001_014_015">unset</a></i>
special built-in command.
<h4><a name = "tag_001_005_001">&nbsp;</a>Positional Parameters</h4>
A positional parameter is a parameter denoted by the decimal value
represented by one or more digits, other than the single digit 0.
The digits denoting the positional parameters are always
interpreted as a decimal value, even if there is a leading zero.
When a positional parameter with more than one digit is
specified, the application must enclose the digits in braces (see
<xref href=parmexp><a href="#tag_001_006_002">
Parameter Expansion
</a></xref>).
Positional parameters are initially assigned when the shell is invoked
(see
<i><a href="sh.html">sh</a></i>),
temporarily replaced when a shell function is invoked (see
<xref href=funccmd><a href="#tag_001_009_005">
Function Definition Command
</a></xref>),
and can be reassigned with the
<i>set</i>
special built-in command.
<h4><a name = "tag_001_005_002">&nbsp;</a>Special Parameters</h4>
<xref type="3" name="specpar"></xref>
Listed below are the
special parameters
and the values to which they will expand.
Only the values of the special parameters are listed;
see
<xref href=wordexp><a href="#tag_001_006">
Word Expansions
</a></xref>
for a detailed summary
of all the stages involved in expanding words.
<dl compact>

<dt><b>*</b><dd>Expands to the positional parameters, starting from one.
When the expansion occurs within a double-quoted string (see
<xref href=dquote><a href="#tag_001_002_003">
Double-quotes
</a></xref>),
it expands to a single
field with the value of each parameter separated by the first
character of the
variable, or by a
space character
if
is unset.
If
is set to a null string, this is not equivalent
to unsetting it; its first character will not exist,
so the parameter values are concatenated.
For example:
<pre>
<code>
<b>$</b> IFS=''
<b>$</b> set foo bar bam
<b>$</b> echo "$@"
<b>foo bar bam</b>
<b>$</b> echo "$*"
<b>foobarbam</b>
<b>$</b> unset IFS
<b>$</b> echo "$*"
<b>foo bar bam</b>
</code>
</pre>

<dt>@<dd>Expands to the positional parameters, starting from one.
When the expansion occurs within double-quotes,
and where field splitting (see
<xref href=fldspl><a href="#tag_001_006_005">
Field Splitting
</a></xref>)
is performed, each positional parameter expands as a separate
field, with the provision that the expansion of the
first parameter is still
joined with the beginning part of the original word
(assuming that the expanded parameter was embedded within a word),
and the expansion of the last parameter is still
joined with the last part of the original word.
If there are no positional parameters, the expansion of "@"
generates zero fields, even when "@" is double-quoted.

<dt>#<dd>Expands to the decimal number of positional parameters.
The command name (parameter
0)
is not counted in the number given by
"#"
because it is a special parameter, not a positional parameter.

<dt><b>?</b><dd>Expands to the decimal exit status of the most recent pipeline (see
<xref href=pipel><a href="#tag_001_009_002">
Pipelines
</a></xref>).

<dt><b>-</b><dd>(Hyphen.)
Expands to the current option flags
(the single-letter option names
concatenated into a string)
as specified on invocation,
by the
<i>set</i>
special built-in command or implicitly by the shell.

The
$-
special parameter can be used to save and restore
<i>set</i>
options:
<pre>
<code>
Save=$(echo $- | sed 's/[ics]//g')
...
set +aCefnuvx
if [ -n "$Save" ]; then
     set -$Save
fi
</code>
</pre>

The three options are removed using
<i><a href="sed.html">sed</a></i>
in the example because they may appear in the value of
$-
(from the
<i><a href="sh.html">sh</a></i>
command line), but are not valid options to
<i>set</i>.

<dt><b>$</b><dd>Expands to the decimal process ID of the invoked shell.
In a subshell (see
<xref href=shexenv><a href="#tag_001_012">
Shell Execution Environment
</a></xref>),
"$" expands to the same value as that of the current shell.

Most historical implementations implement subshells by
forking; thus, the special parameter "$" does not necessarily
represent the process ID of the shell process executing
the commands since the subshell execution environment
preserves the value of "$".

<dt><b>!</b><dd>Expands to the decimal process ID
of the most recent background command (see
<xref href=lists><a href="#tag_001_009_003">
Lists
</a></xref>)
executed from the current shell.
(For example, background commands executed from subshells
do not affect the value of
$!
in the current shell environment.)
For a pipeline, the process ID is that of the last
command in the pipeline.

<dt><b>0</b><dd>(Zero.)
Expands to the name of the shell or shell script.
See
<i><a href="sh.html">sh</a></i>
for a detailed description of how this name is derived.

</dl>
<p>
See the description of the
<i>IFS</i>
variable in
<xref href=shvars><a href="#tag_001_005_003">
Shell Variables
</a></xref>.
<p>
The descriptions of parameters "*" and "@"
assume the reader is familiar with
the field splitting discussion in
<xref href=fldspl><a href="#tag_001_006_005">
Field Splitting
</a></xref>
and understands that portions of the word will
remain concatenated unless there is some reason
to split them into separate fields.
<p>
Some examples of the "*" and "@"
properties, including the concatenation aspects:
<pre>
<code>
set "abc" "def ghi" "jkl"

echo $*        =&gt; "abc" "def" "ghi" "jkl"
echo "$*"      =&gt; "abc def ghi jkl"
echo $@        =&gt; "abc" "def" "ghi" "jkl"
</code>
</pre>
<p>
but:
<pre>
<code>
echo "$@"         =&gt; "abc" "def ghi" "jkl"
echo "xx$@yy"     =&gt; "xxabc" "def ghi" "jklyy"
echo "$@$@"       =&gt; "abc" "def ghi" "jklabc" "def ghi" "jkl"
</code>
</pre>
In the preceding examples, the double-quote
characters that appear after the
=&gt;
do not appear in the output
and are used only to illustrate word boundaries.
<h4><a name = "tag_001_005_003">&nbsp;</a>Shell Variables</h4>
<xref type="3" name="shvars"></xref>
Variables are initialised from the environment
(as defined by the <b>XSH</b> specification)
and can be given new
values with variable assignment commands.
If a variable is initialised from the environment, it is marked
for export immediately; see the
<i><a href="chap2.html#tag_001_014_008">export</a></i>
special built-in.
New variables can be defined and initialised with variable assignments,
with the
<i><a href="read.html">read</a></i>
or
<i><a href="getopts.html">getopts</a></i>
utilities, with the
<i>name</i>
parameter in a
<b>for</b>
loop,
with the
${<i>name=word</i>}
expansion or with other mechanisms
provided as implementation extensions.
The following variables affect the execution of the shell:
<dl compact>

<dt><i>ENV</i><dd>This variable, when the shell is invoked,
is subjected to parameter expansion (see
<xref href=parmexp><a href="#tag_001_006_002">
Parameter Expansion
</a></xref>)
by the shell
and the resulting value is used as a pathname of a
file containing shell commands to execute in the current environment.
The file need not be executable.
If the expanded value of
<i>ENV</i>
is not an absolute pathname, the results are unspecified.
<i>ENV</i>
will be ignored if the user's real and effective user IDs or real and
effective group IDs are different.

This variable can be used to set aliases and other items local
to the invocation of a shell.
The file referred to by
<i>ENV</i>
differs from
<b>$HOME/.profile</b>
in that
<b>.profile</b>
is typically executed at session startup, whereas the
file is executed at the beginning of each
shell invocation.
The
<i>ENV</i>
value is interpreted in a manner similar to a dot script,
in that the commands are executed in the current environment
and the file needs to be readable, but not executable.
However, unlike dot scripts, no
<i>PATH</i>
searching is performed.
This is used as a guard against Trojan Horse security breaches.

<dt><i>HOME</i><dd>This variable is interpreted as the
pathname of the user's home directory.
The contents of
<i>HOME</i>
are used in tilde expansion (see
<xref href=tildexp><a href="#tag_001_006_001">
Tilde Expansion
</a></xref>).

<dt><i>IFS</i><dd><i>Input field separators</i>: a string treated as a list of characters
that is used for field splitting and to
split lines into
fields with the
<i><a href="read.html">read</a></i>
command.
If
<i>IFS</i>
is not set, the shell will behave as if the value of
<i>IFS</i>
were the
space,
tab
and
newline
characters.
(See
<xref href=fldspl><a href="#tag_001_006_005">
Field Splitting
</a></xref>.)

<dt><i>LANG</i><dd>Provide a default value for the internationalisation variables
that are unset or null.
If
<i>LANG</i>
is unset or null, the corresponding value from the
implementation-dependent default locale will be used.
If any of the internationalisation variables contains an invalid setting, the
utility will behave as if none of the variables had been defined.

<dt><i>LC_ALL</i><dd>This variable provides a default value for the
variables, as described in
the <b>XBD</b> specification, 
<a href="../xbd/envvar.html"><b>Environment Variables</b>&nbsp;</a>.

<dt><i>LC_COLLATE</i><dd>This variable determines the behaviour of range
expressions, equivalence classes and multi-character collating elements
within pattern matching.

<dt><i>LC_CTYPE</i><dd>This variable determines the
interpretation of sequences of bytes of text data
as characters (for example, single- as opposed to multi-byte
characters), which characters are defined as
letters (character class
<b>alpha</b>)
and
blank characters
(character class
<b>blank</b>),
and the behaviour of character classes within pattern matching.
Changing the value of
<i>LC_CTYPE</i>
after the shell has started does not affect
the lexical processing of shell commands in the
current shell execution environment or its subshells.
Invoking a shell script or performing
<i><a href="chap2.html#tag_001_014_006">exec</a></i>
<i><a href="sh.html">sh</a></i>
subjects the new shell to the changes in
<i>LC_CTYPE</i>.

<dt><i>LC_MESSAGES</i><dd>This variable determines
the language in which messages should be written.

<dt><i>LINENO</i><dd>This variable is set by the shell to
a decimal number representing the current
sequential line number (numbered starting with 1)
within a script or function before it executes each command.
If the user unsets or resets
<i>LINENO</i>
the variable may lose its special meaning for the life of the shell.
If the shell is not currently executing a script or function, the value of
<i>LINENO</i>
is unspecified.

<dt><i>NLSPATH</i><dd>Determine the location of message catalogues
for the processing of
<i>LC_MESSAGES</i>.

<dt><i>PATH</i><dd>This variable represents a string formatted as described in
the <b>XBD</b> specification, <b>Chapter&nbsp;6</b>, <b>Environment Variables</b>, used to effect command interpretation.
See
<xref href=cmdsea><a href="#tag_001_009_001_001">
Command Search and Execution
</a></xref>.

<dt><i>PPID</i><dd>This variable is set by the shell
to the decimal process ID of the process that invoked this shell.
In a subshell (see
<xref href=shexenv><a href="#tag_001_012">
Shell Execution Environment
</a></xref>),
<i>PPID</i>
will be set to the same
value as that of the parent of the current shell.
For example,
<i><a href="echo.html">echo</a></i>
$PPID
and
(<i>echo</i>
$PPID)
would produce the same value.

Without this variable, there is no way for a utility to signal its parent
or to find its parent process.
This is also useful to know if the shell has been orphaned.

<dt><i>PS1</i><dd>Each time an interactive shell is ready to read a command,
the value of this variable
is subjected to parameter expansion
and written to standard error.
The default value is
"$ ".
For users who have specific
additional implementation-dependent privileges,
the default may be another, implementation-dependent, value.
(Historically, the superuser has had a prompt of
"# ".)
The shell replaces each instance of the character
"!"
in
<i>PS1</i>
with the history file number of the next command to be typed.
Escaping the
"!"
with another
"!"
(that is,
!!)
places the literal character
"!"
in the prompt.

<dt><i>PS2</i><dd>Each time the user enters a
newline character
prior to completing a command line in
an interactive shell,
the value of this variable
is subjected to parameter expansion
and written to standard error.
The default value is
"&gt; ".

<dt><i>PS4</i><dd>When an execution trace
(<i>set</i>
<b>-x</b>)
is being performed in an interactive shell,
before each line in the execution trace,
the value of this variable
is subjected to parameter expansion
and written to standard error.
The default value is
"+ ".

For example, the following script:
<pre>
<code>
PS4='[${LINENO}]+ '
set -x
echo Hello
</code>
</pre>
writes the following to standard error:
<pre>
<code>
[3]+ echo Hello
</code>
</pre>

</dl>
<p>
Tilde expansion for components of the
in an assignment such as:
<pre>
<code>
PATH=~hlj/bin:~dwc/bin:$PATH
</code>
</pre>
is a feature of
some historical shells and is allowed by the wording of
<xref href=tildexp><a href="#tag_001_006_001">
Tilde Expansion
</a></xref>.
Note that the tildes are expanded during the assignment to
<i>PATH</i>
not when
<i>PATH</i>
is accessed during command search.
<hr size=2 noshade>
<h3><a name = "tag_001_006">&nbsp;</a>Word Expansions</h3>
<xref type="2" name="wordexp"></xref>
This section describes the various expansions that are performed on words.
Not all expansions are performed on every word, as explained
in the following sections.
<p>
Tilde expansions, parameter expansions,
command substitutions, arithmetic expansions
and quote removals that occur within a single word
expand to a single field.
It is only field splitting
or pathname expansion that can create multiple fields
from a single word.
The single exception to this rule
is the expansion of the special parameter "@" within
double-quotes, as described in
<xref href=specpar><a href="#tag_001_005_002">
Special Parameters
</a></xref>.
<p>
The order of word expansion is as follows:
<ol>
<p>
<li>
Tilde expansion (see
<xref href=tildexp><a href="#tag_001_006_001">
Tilde Expansion
</a></xref>),
parameter expansion (see
<xref href=parmexp><a href="#tag_001_006_002">
Parameter Expansion
</a></xref>),
command substitution (see
<xref href=cmdsub><a href="#tag_001_006_003">
Command Substitution
</a></xref>),
and arithmetic expansion (see
<xref href=aritexp><a href="#tag_001_006_004">
Arithmetic Expansion
</a></xref>)
are performed, beginning to end.
See item 5 in
<xref href=token><a href="#tag_001_003">
Token Recognition
</a></xref>.
<p>
<li>
Field splitting (see
<xref href=fldspl><a href="#tag_001_006_005">
Field Splitting
</a></xref>)
is performed on the portions of the fields generated by step 1, unless
is null.
<p>
<li>
Pathname expansion (see
<xref href=pathexp><a href="#tag_001_006_006">
Pathname Expansion
</a></xref>)
is performed, unless
<i>set</i>
<b>-f</b>
is in effect.
<p>
<li>
Quote removal (see
<xref href=quoterm><a href="#tag_001_006_007">
Quote Removal
</a></xref>)
always is performed last.
<p>
</ol>
<p>
The expansions described in this section
will occur in the same shell environment
as that in which the command is executed.
<p>
If the complete expansion appropriate for a word results
in an empty field, that empty field will be deleted from
the list of fields that form the completely expanded
command, unless the original word contained
single-quote or double-quote characters.
<p>
The "$" character is used to introduce
parameter expansion, command substitution
or arithmetic evaluation.
If an unquoted "$" is followed by a character that is
either not numeric,
the name of one of the special parameters (see
<xref href=specpar><a href="#tag_001_005_002">
Special Parameters
</a></xref>),
a valid first character of a variable name,
a left curly brace
({)
or a left parenthesis,
the result is unspecified.
<p>
<i>IFS</i>
is used for performing field splitting on the results of parameter
and command substitution;
it is not used for splitting all fields.
Previous versions of the shell
used it for splitting all fields during field splitting,
but this has severe problems
because the shell can no longer parse its own script.
There are also important security implications caused by this behaviour.
All useful applications of
<i>IFS</i>
use it for parsing input of the
<i><a href="read.html">read</a></i>
utility and for splitting the results
of parameter and command substitution.
<p>
The rule concerning expansion to a single field
requires that if
<b>foo=abc</b>
and
<b>bar=def</b>,
that:
<pre>
<code>
"$foo""$bar"
</code>
</pre>
expands to the single field:
<pre>
<code>
abcdef
</code>
</pre>
<p>
The rule concerning empty fields can be illustrated by:
<pre>
<code>
<b>$</b>    unset foo
<b>$</b>    set $foo bar '' xyz "$foo" abc
<b>$</b>    for i
<b>&gt;</b>    do
<b>&gt;</b>        echo "-$i-"
<b>&gt;</b>    done
<b>-bar-
--
-xyz-
--
-abc-</b>
</code>
</pre>
<p>
Step 2 indicates that parameter expansion, command substitution
and arithmetic expansion are all processed simultaneously
as they are scanned.
For example, the following is valid arithmetic:
<pre>
<code>
x=1
echo $(( $(echo 3)+$x ))
</code>
</pre>
<h4><a name = "tag_001_006_001">&nbsp;</a>Tilde Expansion</h4>
<xref type="3" name="tildexp"></xref>
A
<i>tilde-prefix</i>
consists of an unquoted tilde character at the beginning of a word,
followed by
all of the characters preceding the first unquoted slash in the word,
or all the characters in the word if there is no slash.
In an assignment
(see
<b>variable assignment</b>
in the <b>XBD</b> specification, <a href="../xbd/glossary.html"><b>Glossary</b>&nbsp;</a> )
multiple tilde-prefixes can be used:
at the beginning
of the word (that is, following the equal sign of the
assignment), following any unquoted colon or both.
A tilde-prefix in an assignment
is terminated by the first unquoted colon or slash.
If none of the characters in the tilde-prefix are quoted,
the characters in the tilde-prefix
following the tilde are treated as a possible login name
from the user database.
A portable login name cannot contain characters outside
the set given in the description of the
<i>LOGNAME</i>
environment variable in the <b>XSH</b> specification.
If the login name is null
(that is, the tilde-prefix contains only the tilde),
the tilde-prefix will be replaced by the value of the variable
<i>HOME</i>.
If
<i>HOME</i>
is unset, the results are unspecified.
Otherwise, the tilde-prefix will be replaced by a pathname of the
home directory associated with the login name
obtained using the <b>XSH</b> specification
<i><a href="../xsh/getpwnam.html">getpwnam()</a></i>
function.
If the system does not recognise the login name,
the results are undefined.
<p>
Tilde expansion generally occurs only at the beginning
of words, but
an exception based on historical practice has been included:
<pre>
<code>
PATH=/posix/bin:~dgk/bin
</code>
</pre>
is eligible for tilde expansion
because tilde follows a colon
and none of the relevant characters is quoted.
Consideration was given to prohibiting this behaviour
because any of the following are reasonable substitutes:
<pre>
<code>
PATH=$(printf %s: ~rms/bin ~bfox/bin ...)  

PATH=$(printf %s ~karels/bin : ~bostic/bin)

for Dir in ~maart/bin ~srb/bin ...
do
    PATH=${PATH:+$PATH:}$Dir
done
</code>
</pre>
<p>
In the first command, any number of directory names are
concatenated and separated with colons, but it may be
undesirable to end the variable with a colon because this
is an obsolescent means to include dot at the end of the
<i>PATH</i>.
&nbsp;In the second, explicit colons
are used for each directory.
In all cases, the shell performs tilde expansion
on each directory because all are separate words to the shell.
<p>
Note that expressions in operands such as:
<pre>
<code>
make -k mumble LIBDIR=~chet/lib
</code>
</pre>
do not qualify as shell variable assignments
and tilde expansion is not performed (unless the command
does so itself, which
<i><a href="make.html">make</a></i>
does not).
<p>
The special sequence <b>$~</b>
has been designated for future implementations to evaluate
as a means of forcing tilde expansion in any word.
<p>
Because of the requirement that the word is not quoted, the
following are not equivalent; only the last will cause tilde expansion:
<pre>
<code>
\~hlj/   ~h\lj/   ~"hlj"/   ~hlj\/   ~hlj/
</code>
</pre>
<p>
The results of giving tilde with an unknown
login name are undefined because the KornShell
~+
and
~-
constructs make use of this condition, but, in general
it is an error to give an incorrect login name with tilde.
The results of having
<i>HOME</i>
unset are unspecified because some historical shells
treat this as an error.
<h4><a name = "tag_001_006_002">&nbsp;</a>Parameter Expansion</h4>
<xref type="3" name="parmexp"></xref>
The format for parameter expansion is as follows:
<pre>
<code>
${<i>expression</i>}
</code>
</pre>
where
<i>expression</i>
consists of all characters until the matching
"}".
Any
"}"
escaped by a backslash or within a quoted string,
and characters in embedded
arithmetic expansions,
command substitutions
and variable expansions,
are not examined in determining the matching
"}".
<p>
The simplest form for parameter expansion is:
<pre>
<code>
${<i>parameter</i>}
</code>
</pre>
<p>
The value, if any, of
<i>parameter</i>
will be substituted.
<p>
The
parameter
name or symbol can be enclosed in
braces, which are optional except for positional parameters
with more than one digit or when
<i>parameter</i>
is followed by a character that
could be interpreted as part of the name.
The matching closing brace will be determined
by counting brace levels, skipping
over enclosed quoted strings and command substitutions.
<p>
If the parameter name or symbol is not enclosed in braces,
the expansion will use the longest
valid name (see <b>name</b>
in the <b>XBD</b> specification, <a href="../xbd/glossary.html"><b>Glossary</b>&nbsp;</a> ),
whether or not the symbol represented by that name exists.
When the shell is scanning its input to determine the boundaries
of a name, it is not bound by its knowledge of what names
are already defined.
For example, if
<b>F</b>
is a defined shell variable, the command:
<pre>
<code>
echo&nbsp;$Fred
</code>
</pre>
does not echo the value of
<b>$F</b>
followed by
<b>red</b>;
it selects the longest possible valid name,
<b>Fred</b>,
which in this case might be unset.
<p>
If a parameter expansion occurs inside double-quotes:
<ul>
<p>
<li>
Pathname expansion will not be performed
on the results of the expansion.
<p>
<li>
Field splitting will not be performed
on the results of the expansion,
with the exception of "@"; see
<xref href=specpar><a href="#tag_001_005_002">
Special Parameters
</a></xref>.
<p>
</ul>
<p>
In addition, a
parameter expansion
can be modified by using one of the following formats.
In each case
that a value of
<i>word</i>
is needed (based on the state of
<i>parameter</i>,
as described below),
<i>word</i>
will be subjected to
tilde expansion,
parameter expansion, command substitution
and arithmetic expansion.
If
<i>word</i>
is not needed, it will not be expanded.
The
"}"
character that delimits the following parameter expansion
modifications is determined
as described previously in this section and in
<xref href=dquote><a href="#tag_001_002_003">
Double-quotes
</a></xref>.
(For example,
${foo-bar}xyz}
would result in the expansion of
<b>foo</b>
followed by the string
xyz}
if
<b>foo</b>
is set, else the string
barxyz}).
<dl compact>

<dt>${<i>parameter</i>:-<i>word</i>}<dd><b>Use Default Values</b>. If
<i>parameter</i>
is unset or null, the expansion of
<i>word</i>
will be substituted; otherwise, the value of
<i>parameter</i>
will be substituted.

<dt>${<i>parameter</i>:=<i>word</i>}<dd><b>Assign Default Values</b>. If
<i>parameter</i>
is unset or null, the expansion of
<i>word</i>
will be assigned to
<i>parameter</i>.
In all cases, the final value of
<i>parameter</i>
will be substituted.
Only variables, not positional parameters or special parameters,
can be assigned in this way.

<dt>${<i>parameter</i>:?<b>[</b><i>word</i><b>]</b>}<dd><b>Indicate Error if Null or Unset</b>. If
<i>parameter</i>
is unset or null, the expansion of
<i>word</i>
(or a message indicating it is unset if
<i>word</i>
is omitted)
will be written to
standard error and the shell will exit
with a non-zero exit status.
Otherwise, the value of
<i>parameter</i>
will be substituted.
An interactive shell
need not exit.

<dt>${<i>parameter</i>:+<i>word</i>}<dd><b>Use Alternative Value</b>. If
<i>parameter</i>
is unset or null,
null will be substituted;
otherwise, the expansion of
<i>word</i>
will be substituted.

</dl>
<p>
In the parameter expansions shown previously,
use of the colon in the format results in a test
for a parameter that is unset or null;
omission of the colon results in a test
for a parameter that is only unset.
The following table summarises the effect of the colon:
<pre>
<table  bordercolor=#000000 border=1 align=center><tr valign=top><th align=center><b>&nbsp;</b>
<th align=center><b>parameter<br>set and not null</b>
<th align=center><b>parameter<br>set but null</b>
<th align=center><b>parameter<br>unset</b>
<tr valign=top><td align=left><b>${</b><i>parameter</i><b>:-</b><i>word</i><b>}</b>
<td align=left>substitute <i>parameter</i>
<td align=left>substitute <i>word</i>
<td align=left>substitute <i>word</i>
<tr valign=top><td align=left><b>${</b><i>parameter</i><b>-</b><i>word</i><b>}</b>
<td align=left>substitute <i>parameter</i>
<td align=left>substitute null
<td align=left>substitute <i>word</i>
<tr valign=top><td align=left><b>${</b><i>parameter</i><b>:=</b><i>word</i><b>}</b>
<td align=left>substitute <i>parameter</i>
<td align=left>assign <i>word</i>
<td align=left>assign <i>word</i>
<tr valign=top><td align=left><b>${</b><i>parameter</i><b>=</b><i>word</i><b>}</b>
<td align=left>substitute <i>parameter</i>
<td align=left>substitute <i>parameter</i>
<td align=left>assign null
<tr valign=top><td align=left><b>${</b><i>parameter</i><b>:?</b><i>word</i><b>}</b>
<td align=left>substitute <i>parameter</i>
<td align=left>error, exit
<td align=left>error, exit
<tr valign=top><td align=left><b>${</b><i>parameter</i><b>?</b><i>word</i><b>}</b>
<td align=left>substitute <i>parameter</i>
<td align=left>substitute null
<td align=left>error, exit
<tr valign=top><td align=left><b>${</b><i>parameter</i><b>:+</b><i>word</i><b>}</b>
<td align=left>substitute <i>word</i>
<td align=left>substitute null
<td align=left>substitute null
<tr valign=top><td align=left><b>${</b><i>parameter</i><b>+</b><i>word</i><b>}</b>
<td align=left>substitute <i>word</i>
<td align=left>substitute <i>word</i>
<td align=left>substitute null
</table>
</pre>
<p>
In all cases shown with &quot;substitute&quot;,
the expression is replaced with the value shown.
In all cases shown with &quot;assign&quot;,
<i>parameter</i>
is assigned that value, which also replaces the expression.
<dl compact>

<dt><b>${#</b><i>parameter</i><b>}</b><dd><b>String Length</b>. The length in characters of the value of
<i>parameter</i>.
If
<i>parameter</i>
is "*" or "@",
the result of the expansion is unspecified.

</dl>
<p>
The following four varieties of parameter expansion
provide for substring processing.
In each case, pattern matching notation (see
<xref href=patmat><a href="#tag_001_013">
Pattern Matching Notation
</a></xref>),
rather than regular expression notation, will be
used to evaluate the patterns.
If
<i>parameter</i>
is "*" or "@", the result of the expansion is unspecified.
Enclosing the full parameter expansion string in
double-quotes will not cause the following four
varieties of pattern characters
to be quoted, whereas
quoting characters within the braces will have this effect.
<dl compact>

<dt>${<i>parameter</i>%<i>word</i>}<dd><b>Remove Smallest Suffix Pattern</b>.
The
<i>word</i>
will be expanded to produce a pattern.
The parameter expansion then will result in
<i>parameter</i>,
with the smallest portion of the suffix matched by the
<i>pattern</i>
deleted.

<dt>${<i>parameter</i>%%<i>word</i>}<dd><b>Remove Largest Suffix Pattern</b>.
The
<i>word</i>
will be expanded to produce a pattern.
The parameter expansion then will result in
<i>parameter</i>,
with the largest portion of the suffix matched by the
<i>pattern</i>
deleted.

<dt>${<i>parameter</i>#<i>word</i>}<dd><b>Remove Smallest Prefix Pattern</b>. The
<i>word</i>
will be expanded to produce a pattern.
The parameter expansion then will result in
<i>parameter</i>,
with the smallest portion of the prefix matched by the
<i>pattern</i>
deleted.

<dt>${<i>parameter</i>##<i>word</i>}<dd><b>Remove Largest Prefix Pattern</b>. The
<i>word</i>
will be expanded to produce a pattern.
The parameter expansion then will result in
<i>parameter</i>,
with the largest portion of the prefix matched by the
<i>pattern</i>
deleted.

</dl>
<p>
<h5><a name = "tag_001_006_002_001">&nbsp;</a>Examples</h5>
<dl compact>

<dt>${<i>parameter</i>:-<i>word</i>}<dd>
In this example,
<i><a href="ls.html">ls</a></i>
is executed only if
x
is null or unset.
(The
$(ls)
command substitution notation is explained in
<xref href=cmdsub><a href="#tag_001_006_003">
Command Substitution
</a></xref>.)
<pre>
<code>
${x:-$(ls)}
</code>
</pre>

<dt>${<i>parameter</i>:=<i>word</i>}<dd><code>
<pre>
unset X
echo ${X:=abc}
<b>abc
</b></code>
</pre>

<dt>${<i>parameter</i>:?<i>word</i>}<dd><code>
<pre>
unset posix
echo ${posix:?}
<b>sh: posix: parameter null or not set
</b></code>
</pre>

<dt>${<i>parameter</i>:<i>word</i>}<dd><code>
<pre>
set a b c
echo ${3:+posix}
<b>posix
</b></code>
</pre>

<dt><b>${#</b><i>parameter</i><b>}<dd></b><code>
<pre>
HOME=/usr/posix
echo ${#HOME}
<b>10
</b></code>
</pre>

<dt>${<i>parameter</i>%<i>word</i>}<dd><code>
<pre>
x=file.c
echo ${x%.c}.o
<b>file.o
</b></code>
</pre>

<dt>${<i>parameter</i>%%<i>word</i>}<dd><code>
<pre>
x=posix/src/std
echo ${x%%/*}
<b>posix
</b></code>
</pre>

<dt>${<i>parameter</i>#<i>word</i>}<dd><code>
<pre>
x=$HOME/src/cmd
echo ${x#$HOME}
<b>/src/cmd
</b></code>
</pre>

<dt>${<i>parameter</i>##<i>word</i>}<dd><code>
<pre>
x=/one/two/three
echo ${x##*/}
<b>three
</b></code>
</pre>

</dl>
<p>
The double-quoting of patterns is different depending on where the
double-quotes are placed:
<dl compact>

<dt>${x#*}<dd>The asterisk is a pattern character.

<dt>${x#"*"}<dd>The literal asterisk is quoted and not special.

</dl>
<h4><a name = "tag_001_006_003">&nbsp;</a>Command Substitution</h4>
<xref type="3" name="cmdsub"></xref>
Command substitution
allows the output of a command to be substituted
in place of the command name itself.
Command substitution occurs when the command is enclosed as follows:
<pre>
<code>
$(<i>command</i>)
</code>
</pre>
or (backquoted version):
<pre>
<code>
`<i>command</i>`
</code>
</pre>
<p>
The shell will expand the command substitution
by executing
<i>command</i>
in a subshell environment (see
<xref href=shexenv><a href="#tag_001_012">
Shell Execution Environment
</a></xref>)
and replacing the command substitution
(the text of
<i>command</i>
plus the enclosing
$()
or backquotes)
with the standard output of the command,
removing sequences of one or more
newline characters
at the end of the substitution.
Embedded
newline characters
before the end of the output will not be removed;
however, they may be treated as field delimiters and eliminated
during field splitting,
depending on the value of
and quoting that is in effect.
<p>
Within the backquoted style of command substitution,
backslash shall retain its literal meaning, except when followed by:
<pre>
<code>
$   `   \
</code>
</pre>
<p>
(dollar-sign, backquote, backslash).
The search for the matching backquote
is satisfied by the first backquote
found without a preceding backslash;
during this search,
if a non-escaped backquote is encountered
within a shell comment, a here-document,
an embedded command substitution of the $(<i>command</i>) form,
or a quoted string, undefined results occur.
A single- or double-quoted string that begins, but does not end, within the
`...` sequence produces undefined results.
<p>
With the $(<i>command</i>)
form, all characters following the open parenthesis to the matching
closing parenthesis constitute the
<i>command</i>.
Any valid shell script can be used for
<i>command</i>,
except:
<ul>
<p>
<li>
a script consisting solely of redirections produces unspecified results
<p>
<li>
see the restriction on single subshells described below.
<p>
</ul>
<p>
The results of command substitution will not be
field splitting and pathname expansion
processed for further
tilde expansion, parameter expansion, command substitution
or arithmetic expansion.
If a command substitution occurs inside double-quotes, it
will not be performed on the results of the substitution.
<p>
Command substitution can be nested.
To specify nesting within the backquoted version,
the application must precede the inner backquotes with
backslashes;
for example:
<pre>
<code>
\`<i>command</i>\`
</code>
</pre>
<p>
The
$()
form of command substitution
solves a problem of inconsistent behaviour when using backquotes.
For example:
<p><table  bordercolor=#000000 border=1 align=center><tr valign=top><th align=center><b>Command</b>
<th align=center><b>Output</b>
<tr valign=top><td align=left>echo '\$x'
<td align=left>\$x
<tr valign=top><td align=left>echo `echo '\$x'`
<td align=left>$x
<tr valign=top><td align=left>echo $(echo '\$x')
<td align=left>\$x
</table>
<p>
Additionally, the backquoted syntax has historical restrictions
on the contents of the embedded command.
While the new
$()
form can process any kind of valid embedded script,
the backquoted form cannot handle some valid scripts that
include backquotes.
For example, these otherwise valid embedded scripts
do not work in the left column, but do work on the right:
<pre>
<code>
echo `                         echo $(
cat &lt;&lt;\eof                     cat &lt;&lt;\eof
a here-doc with `              a here-doc with )
eof                            eof
`                              )

echo `                         echo $(
echo abc # a comment with `    echo abc # a comment with )
`                              )

echo `                         echo $(
echo '`'                       echo ')'
`                              )
</code>
</pre>
<p>
Because of these inconsistent behaviours,
the backquoted variety of command substitution
is not recommended for new applications that nest command substitutions
or attempt to embed complex scripts.
<p>
If the command substitution consists of a single subshell, such as:
<pre>
<code>
$( (<i>command</i>) )
</code>
</pre>
a portable application must separate the
$(
and
"("
into two tokens (that is, separate them with white space).
This is required to
avoid any ambiguities with arithmetic expansion.
<h4><a name = "tag_001_006_004">&nbsp;</a>Arithmetic Expansion</h4>
<xref type="3" name="aritexp"></xref>
Arithmetic expansion provides a mechanism for evaluating
an arithmetic expression and substituting its value.
The format for arithmetic expansion is as follows:
<pre>
<code>
$((<i>expression</i>))
</code>
</pre>
<p>
The expression is treated as if it were in double-quotes,
except that a double-quote inside the expression is not
treated specially.
The shell will expand all tokens in the expression
for parameter expansion, command substitution
and quote removal.
<p>
Next, the shell will treat this as an arithmetic expression
and substitute the value of the expression.
The arithmetic expression will be processed
according to the rules of the ISO&nbsp;C standard,
with the following exceptions:
<ul>
<p>
<li>
Only integer arithmetic is required.
<p>
<li>
The
sizeof()
operator and the prefix and postfix
++
and
--
operators are not required.
<p>
<li>
Selection, iteration and jump statements are not supported.
<p>
</ul>
<p>
As an extension, the shell may recognise arithmetic expressions
beyond those listed.
If the expression is invalid, the
expansion will fail and the shell
will write a message to standard error indicating the failure.
<p>
A simple example using arithmetic expansion:
<pre>
<code>
# repeat a command 100 times
x=100
while [ $x -gt 0 ]
do
    <i>command</i>
    x=$(($x-1))
done
</code>
</pre>
<h4><a name = "tag_001_006_005">&nbsp;</a>Field Splitting</h4>
<xref type="3" name="fldspl"></xref>
After parameter expansion,
command substitution,
and arithmetic expansion 
the shell will scan the results of expansions and substitutions
that did not occur in double-quotes for
field splitting and multiple fields can result.
<p>
The shell will treat each character of the
<i>IFS</i>
as a delimiter and use the delimiters to split the results of
parameter expansion and command substitution into
fields.
<ol>
<p>
<li>
If the value of
<i>IFS</i>
is a space, tab and newline character, or if it is unset,
any sequence of space, tab or newline
characters at the beginning or end of the input
will be ignored and any sequence
of those characters within the input will delimit a field.
For example, the input:
<pre>
<code>
&lt;newline&gt;&lt;space&gt;&lt;tab&gt;foo&lt;tab&gt;&lt;tab&gt;bar&lt;space&gt;
</code>
</pre>
yields two fields,
<b>foo</b>
and
<b>bar</b>.
<p>
<li>
If the value of
<i>IFS</i>
is null, no field splitting will be performed.
<p>
<li>
Otherwise, the following rules will be applied in sequence.
The term
&quot;<i>IFS</i>
white space&quot; is used to mean any sequence (zero or more instances) of
white-space characters that are in the
<i>IFS</i>
value (for example, if
<i>IFS</i>
contains space/comma/tab, any sequence of space and tab
characters is considered
<i>IFS</i>
white space).
<ol type = a>
<p>
<li>
<i>IFS</i>
white space is ignored at the beginning and end
of the input.
<p>
<li>
Each occurrence in the input of an
<i>IFS</i>
character that is not
<i>IFS</i>
white space, along with any adjacent
<i>IFS</i>
white space,
will delimit a field, as described previously.
<p>
<li>
Non-zero-length
<i>IFS</i>
white space will delimit a field.
<p>
</ol>
<p>
</ol>
<p>
The last rule can be summarised as a pseudo-ERE:
<pre>
<code>
(<i>s</i>*<i>ns</i>*|<i>s</i>+)
</code>
</pre>
where <i>s</i> is an
white-space character and <i>n</i> is a character in the
that is not white space.
Any string matching that ERE delimits a field, except that the <i>s</i>+
form does not delimit fields at the beginning or the end of a line.
For example, if
<i>IFS</i>
is space/comma/tab, the string:
<pre>
<code>
&lt;space&gt;&lt;space&gt;red&lt;space&gt;&lt;space&gt;,&lt;space&gt;white&lt;space&gt;blue
</code>
</pre>
yields the three colours as the delimited fields.
<h4><a name = "tag_001_006_006">&nbsp;</a>Pathname Expansion</h4>
<xref type="3" name="pathexp"></xref>
After field splitting, if
<i>set</i>
<b>-f</b>
is not in effect,
each field in the resulting command line will be
expanded using the algorithm described in
<xref href=patmat><a href="#tag_001_013">
Pattern Matching Notation
</a></xref>,
qualified by the rules in
<xref href=patfilx><a href="#tag_001_013_003">
Patterns Used for Filename Expansion
</a></xref>.
<h4><a name = "tag_001_006_007">&nbsp;</a>Quote Removal</h4>
<xref type="3" name="quoterm"></xref>
The quote characters:
<pre>
<code>
\   '   "
</code>
</pre>
<p>
(backslash, single-quote, double-quote)
that were present in the original word
will be removed unless they have themselves been quoted.
<hr size=2 noshade>
<h3><a name = "tag_001_007">&nbsp;</a>Redirection</h3>
<xref type="2" name="redir"></xref>
Redirection is used to open and close files for the current
shell execution environment (see
<xref href=shexenv><a href="#tag_001_012">
Shell Execution Environment
</a></xref>)
or for any command.
<i>Redirection operators</i>
can be used with numbers representing
file descriptors (see the definition in the ISO&nbsp;POSIX-1 standard)
as described below.
<p>
The overall format used for redirection is:
<code>
<p>
<b>[</b><i>n</i><b>]</b><i>redir-op</i>   <i>word</i>
</code>
<p>
The number
<i>n</i>
is an optional decimal number designating
the file descriptor number; it must be delimited
from any preceding text and immediately precede the
redirection operator
<i>redir-op</i>.
If
<i>n</i>
is quoted, the number will not be recognised as part of the
redirection expression.
For example:
<pre>
<code>
echo&nbsp;\2&gt;a
</code>
</pre>
writes the character
2
into file <b>a</b>.
If any part of
<i>redir-op</i>
is quoted, no redirection expression will be recognised.
For example:
<pre>
<code>
echo&nbsp;2\&gt;a
</code>
</pre>
writes the characters
2&gt;a
to standard output.
The optional number, redirection operator and
<i>word</i>
will not appear in the
arguments provided to the command to be executed (if any).
<p>
Open files are represented by decimal numbers
starting with zero.
The largest possible value is implementation-dependent;
however, all implementations support at least 0 to 9, inclusive,
for use by the application.
These numbers are called
<i>file descriptors</i>.
The values 0, 1 and 2
have special meaning and conventional uses
and are implied by certain redirection operations;
they are referred to as
<i>standard input</i>, <i>standard output</i>
and
<i>standard error</i>,
respectively.
Programs usually take their input from standard input,
and write output on standard output.
Error messages are usually written on standard error.
The redirection operators can be preceded by
one or more digits (with
no intervening
blank characters
allowed)
to designate the file descriptor number.
<p>
If the redirection operator is
&lt;&lt;
or
&lt;&lt;-,
the word that follows the redirection operator will be subjected to
quote removal;
it is unspecified whether any of the other expansions occur.
For the other redirection operators,
the word that follows the redirection operator will be subjected to
tilde expansion, parameter expansion, command substitution,
arithmetic expansion and quote removal.
Pathname expansion will not be performed on the word by a non-interactive shell;
an interactive shell may perform it, but will do so only when the
expansion would result in one word.
<p>
If more than one redirection operator is specified
with a command, the order of evaluation is from beginning to end.
<p>
A failure to open or create a file will cause the redirection to fail.
<h4><a name = "tag_001_007_001">&nbsp;</a>Redirecting Input</h4>
Input redirection will cause the file whose name results from the expansion of
<i>word</i>
to be opened for reading
on the designated file descriptor, or standard input if
the file descriptor is not specified.
<p>
The general format for redirecting input is:
<pre>
<code>
<b>[</b><i>n</i><b>]</b>&lt;<i>word</i>
</code>
</pre>
where the optional
<i>n</i>
represents the file descriptor number.
If the number is omitted,
the redirection will refer to standard input (file descriptor
0).
<h4><a name = "tag_001_007_002">&nbsp;</a>Redirecting Output</h4>
<xref type="3" name="rediro"></xref>
The two general formats for redirecting output are:
<pre>
<code>
<b>[</b><i>n</i><b>]</b>&gt;<i>word</i>
<b>[</b><i>n</i><b>]</b>&gt;|<i>word</i>
</code>
</pre>
where the optional
<i>n</i>
represents the file descriptor number.
If the number is omitted,
the redirection will refer to standard output (file descriptor
1).
<p>
Output redirection using the
"&gt;"
format will fail if the
<i>noclobber</i>
option is set (see the description of
<i>set</i>
<b>-C</b>)
and the file named by the expansion of
<i>word</i>
exists and is a regular file.
Otherwise, redirection using the
"&gt;"
or
&gt;|
formats will cause the file whose
name results from the expansion of
<i>word</i>
to be created
and opened for output on the designated file descriptor,
or standard output if none is specified.
If the file
does not exist, it will be created; otherwise, it will
be truncated to be an empty file after being opened.
<h4><a name = "tag_001_007_003">&nbsp;</a>Appending Redirected Output</h4>
Appended output redirection will cause the file whose name
results from the expansion of word to be opened for output
on the designated file descriptor.
The file is opened as if the <b>XSH</b> specification
<i><a href="../xsh/open.html">open()</a></i>
function was called with the O_APPEND flag.
If the file does not exist, it will be created.
<p>
The general format for appending redirected output is as follows:
<pre>
<code>
<b>[</b><i>n</i><b>]</b>&gt;&gt;<i>word</i>
</code>
</pre>
where the optional
<i>n</i>
represents the file descriptor number.
<h4><a name = "tag_001_007_004">&nbsp;</a>Here-document</h4>
<xref type="3" name="heredoc"></xref>
The redirection operators
&lt;&lt;
and
&lt;&lt;-
both allow redirection of lines contained in a shell input file, known
as a
<i>here-document</i>,
to the standard input
of a command.
<p>
The here-document is treated as a single word that begins after the next
newline character
and continues until there is a line
containing only the delimiter,
with no trailing
blank characters.
Then the next here-document starts, if there is one.
The format is as follows:
<pre>
<code>
<b>[</b><i>n</i><b>]</b>&lt;&lt;<i>word
    here-document
delimiter</i>
</code>
</pre>
<p>
If any character in
<i>word</i>
is quoted, the delimiter is formed by performing quote removal on
<i>word</i>,
and the here-document lines will not be expanded.
Otherwise, the delimiter is the
<i>word</i>
itself.
<p>
If no characters in
<i>word</i>
are quoted, all lines of the here-document will be expanded
for parameter expansion, command substitution and
arithmetic expansion.
In this case, the backslash
in the input will behave as the backslash inside double-quotes (see
<xref href=dquote><a href="#tag_001_002_003">
Double-quotes
</a></xref>).
However, the double-quote character (<b>"</b>)
will not be treated specially within a here-document,
except when the double-quote appears within
$(&nbsp;),
`&nbsp;`
or
${&nbsp;}.
<p>
If the redirection symbol is
&lt;&lt;-,
all leading
tab
characters will be stripped from input lines and the line containing the
trailing delimiter.
If more than one
&lt;&lt;
or
&lt;&lt;-
operator is specified on a line,
the here-document
associated with the first operator
will be supplied first by the application and
will be read first by the shell.
For example:
<pre>
<code>
cat &lt;&lt;eof1; cat &lt;&lt;eof2
Hi,
eof1
Helene.
eof2
</code>
</pre>
<p>
The case of a missing delimiter at the end of a here-document
is not specified.
This is considered an error in the script
(one that sometimes can be difficult to diagnose),
although some systems have treated end-of-file
as an implicit delimiter.
<h4><a name = "tag_001_007_005">&nbsp;</a>Duplicating an Input File Descriptor</h4>
The redirection operator:
<pre>
<code>
<b>[</b><i>n</i><b>]</b>&lt;&amp;<i>word</i>
</code>
</pre>
is used to duplicate one input file descriptor from
another, or to close one.
If
<i>word</i>
evaluates to one
or more digits, the file descriptor denoted by
<i>n</i>,
or standard input if
<i>n</i>
is not specified, will be made to
be a copy of the file descriptor denoted by
<i>word</i>;
if the digits in
<i>word</i>
do not represent a file descriptor already open for input,
a redirection error will result (see
<xref href=sherr><a href="#tag_001_008_001">
Consequences of Shell Errors
</a></xref>).
If
<i>word</i>
evaluates to "-", file descriptor
<i>n</i>,
or standard input if
<i>n</i>
is not specified, will be closed.
If
<i>word</i>
evaluates to something else, the behaviour is unspecified.
<h4><a name = "tag_001_007_006">&nbsp;</a>Duplicating an Output File Descriptor</h4>
The redirection operator:
<pre>
<code>
<b>[</b><i>n</i><b>]</b>&gt;&amp;<i>word</i>
</code>
</pre>
is used to duplicate one output file descriptor from
another, or to close one.
If
<i>word</i>
evaluates to one
or more digits, the file descriptor denoted by
<i>n</i>,
or standard output if
<i>n</i>
is not specified, will be made to
be a copy of the file descriptor denoted by
<i>word</i>;
if the digits in
<i>word</i>
do not represent a file descriptor already open for output,
a redirection error will result (see
<xref href=sherr><a href="#tag_001_008_001">
Consequences of Shell Errors
</a></xref>).
If
<i>word</i>
evaluates to "-", file descriptor
<i>n</i>,
or standard output if
<i>n</i>
is not specified, will be closed.
If
<i>word</i>
evaluates to something else, the behaviour is unspecified.
<p>
The construct
2&gt;&amp;1
is often used to redirect standard
error to the same file as standard output.
Since the redirections
take place beginning to end, the order of redirections is significant.
For example:
<pre>
<code>
ls &gt; foo 2&gt;&amp;1
</code>
</pre>
directs both standard output and standard error to file
<b>foo</b>.
However:
<pre>
<code>
ls 2&gt;&amp;1 &gt; foo
</code>
</pre>
only directs standard output to file
<b>foo</b>
because standard error was duplicated as standard output before standard
output was directed to file
<b>foo</b>.
<h4><a name = "tag_001_007_007">&nbsp;</a>Open File Descriptors for Reading and Writing</h4>
The redirection operator:
<pre>
<code>
<b>[</b><i>n</i><b>]</b>&lt;&gt;<i>word</i>
</code>
</pre>
will cause the file whose name is the expansion of
<i>word</i>
to be opened for both reading and writing on the file
descriptor denoted by
<i>n</i>,
or standard input if
<i>n</i>
is not specified.
If the file does not exist, it will be created.
<p>
The
&lt;&gt;
operator
could be useful in writing
an application that worked with several terminals, and occasionally wanted
to start up a shell.
That shell would in turn be unable to run applications that run from an
ordinary controlling terminal
unless it could make use of
&lt;&gt;
redirection.
The specific example is a historical version of the pager
<i><a href="more.html">more</a></i>,
which reads from standard error to get its commands, so standard input
and standard output are both available for their usual usage.
There is no way of saying the following in the shell without
&lt;&gt;:
<pre>
<code>
cat food | more - &gt;/dev/tty03 2&lt;&gt;/dev/tty03
</code>
</pre>
<p>
Another example of
&lt;&gt;
is one that opens
<b>/dev/tty</b>
on file descriptor 3 for reading and writing:
<pre>
<code>
exec 3&lt;&gt; /dev/tty
</code>
</pre>
<p>
An example of creating a lock file for a critical code region:
<pre>
<code>
set -C
until    2&gt; /dev/null &gt; lockfile
do       sleep 30
done
set +C
<i>perform critical function</i>
rm lockfile
</code>
</pre>
<p>
Since
<b>/dev/null</b>
is not a regular file, no error is generated
by redirecting to it in
<i>noclobber</i>
mode.
<p>
<hr size=2 noshade>
<h3><a name = "tag_001_008">&nbsp;</a>Exit Status and Errors</h3>
<h4><a name = "tag_001_008_001">&nbsp;</a>Consequences of Shell Errors</h4>
<xref type="3" name="sherr"></xref>
For a non-interactive shell, an error condition
encountered by a special built-in (see
<xref href=sbi><a href="#tag_001_014">
Special Built-in Utilities
</a></xref>)
or other type of utility will cause the
shell to write a diagnostic message to
standard error and exit as shown in the following table:
<pre>
<table  bordercolor=#000000 border=1 align=center><tr valign=top><th align=center><b>Error</b>
<th align=center><b>Special Built-in</b>
<th align=center><b>Other Utilities</b>
<tr valign=top><td align=left>Shell language syntax error
<td align=left>will exit
<td align=left>will exit
<tr valign=top><td align=left>Utility syntax error (option or operand error)
<td align=left>will exit
<td align=left>will not exit
<tr valign=top><td align=left>Redirection error
<td align=left>will exit
<td align=left>will not exit
<tr valign=top><td align=left>Variable assignment error
<td align=left>will exit
<td align=left>will not exit
<tr valign=top><td align=left>Expansion error
<td align=left>will exit
<td align=left>will exit
<tr valign=top><td align=left>Command not found
<td align=left>n/a
<td align=left>may exit
<tr valign=top><td align=left>Dot script not found
<td align=left>will exit
<td align=left>n/a
</table>
</pre>
An expansion error is one that occurs when the shell expansions
defined in
<xref href=wordexp><a href="#tag_001_006">
Word Expansions
</a></xref>
are carried out (for example,
${x!y},
because
"!"
is not a valid operator);
an implementation may treat these as syntax errors
if it is able to detect them during tokenisation,
rather than during expansion.
<p>
If any of the errors shown as &quot;will (may) exit&quot; occur in a subshell,
the subshell will (may) exit with a non-zero status, but the script
containing the subshell will not exit because of the error.
<p>
In all of the cases shown in the table,
an interactive shell will write a diagnostic message to standard error
without exiting.
<h4><a name = "tag_001_008_002">&nbsp;</a>Exit Status for Commands</h4>
<xref type="3" name="existat"></xref>
Each command has an exit status that can influence
the behaviour of other shell commands.
The exit status of commands that are not utilities is documented
in this section.
The exit status of the standard utilities is documented in
their respective sections.
<p>
If a command is not found, the exit status will be 127.
If the command name is found, but it
is not an executable utility, the exit status will be 126.
Applications that invoke utilities without using the shell
should use these exit status values
to report similar errors.
<p>
If a command fails during word expansion or redirection,
its exit status will be greater than zero.
<p>
Internally, for purposes of deciding if a command
exits with a non-zero exit status,
the shell will recognise the
entire status value retrieved for the command
by the equivalent of the <b>XSH</b> specification
<i><a href="../xsh/wait.html">wait()</a></i>
function WEXITSTATUS macro.
When reporting the exit status with the special parameter ?,
the shell will report the full eight bits of exit status available.
The exit status of a command that terminated
because it received a signal will be reported as greater than 128.
<p>
<hr size=2 noshade>
<h3><a name = "tag_001_009">&nbsp;</a>Shell Commands</h3>
<xref type="2" name="shcmds"></xref>
This section describes the basic structure of shell commands.
The following command descriptions each describe a
format of the command that is only used
to aid the reader in recognising the command type,
and does not formally represent the syntax.
Each description discusses the semantics of the
command; for a formal definition of the command
language, consult
<xref href=shgram><a href="#tag_001_010">
Shell Grammar
</a></xref>.
<p>
A
<i>command</i>
is one of the following:
<ul>
<p>
<li>
<i>simple command</i>
(see
<xref href=simpcmd><a href="#tag_001_009_001">
Simple Commands
</a></xref>)
<p>
<li>
<i>pipeline</i>
(see
<xref href=pipel><a href="#tag_001_009_002">
Pipelines
</a></xref>)
<p>
<li>
<i>list</i>
or
<i>compound-list</i>
(see
<xref href=lists><a href="#tag_001_009_003">
Lists
</a></xref>)
<p>
<li>
<i>compound command</i>
(see
<xref href=compcmd><a href="#tag_001_009_004">
Compound Commands
</a></xref>)
<p>
<li>
<i>function definition</i>
(see
<xref href=funccmd><a href="#tag_001_009_005">
Function Definition Command
</a></xref>).
<p>
</ul>
<p>
Unless otherwise stated,
the exit status of a command is that of the
last simple command executed by the command.
There is no limit on the size of any shell command other
than that imposed by the underlying system (memory constraints,
{ARG_MAX},
and so on).
<h4><a name = "tag_001_009_001">&nbsp;</a>Simple Commands</h4>
<xref type="3" name="simpcmd"></xref>
A
<i>simple command</i>
is a sequence of optional variable assignments
and redirections,
in any sequence,
optionally followed by words and redirections,
terminated by a control operator.
<p>
When a given simple command is required to be executed
(that is, when any conditional construct such as an AND-OR list or a
<b>case</b>
statement has not bypassed the simple command),
the following expansions, assignments and redirections will all be
performed from the beginning
of the command text to the end.
<ol>
<p>
<li>
The words that are recognised as
variable assignments or redirections according to
<xref href=shgramr><a href="#tag_001_010_002">
Shell Grammar Rules
</a></xref>
are saved for processing in steps 3 and 4.
<p>
<li>
The words that are not variable assignments or redirections will be expanded.
If any fields remain following
their expansion, the first field will be considered the command
name and remaining fields will be the arguments for the command.
<p>
<li>
Redirections will be performed as described in
<xref href=redir><a href="#tag_001_007">
Redirection
</a></xref>.
<p>
<li>
Each variable assignment will be expanded for
tilde expansion, parameter expansion,
command substitution, arithmetic expansion and
quote removal prior to assigning the value.
<p>
</ol>
<p>
In the preceding list, the order of steps 3 and 4 may be reversed for
the processing of special built-in utilities.
See
<xref href=sbi><a href="#tag_001_014">
Special Built-in Utilities
</a></xref>.
<p>
If no command name results, variable assignments will affect
the current execution environment.
Otherwise, the
variable assignments will be exported for the execution environment
of the command and will not affect the current execution environment
(except for special built-ins).
If any of the variable assignments
attempt to assign a value to a read-only variable,
a variable assignment error will occur.
See
<xref href=sherr><a href="#tag_001_008_001">
Consequences of Shell Errors
</a></xref>
for the consequences of these errors.
<p>
If there is no command name, any redirections will be performed
in a subshell environment;
it is unspecified whether this subshell environment
is the same one as that used for a command substitution
within the command.
(To affect the current execution environment, see the
<i><a href="chap2.html#tag_001_014_006">exec</a></i>
special built-in.)
If any of the redirections performed in the current
shell execution environment fail,
the command will immediately fail with an exit status greater than zero,
and the shell will write an error message indicating the failure.
See
<xref href=sherr><a href="#tag_001_008_001">
Consequences of Shell Errors
</a></xref>
for the consequences of these failures on
interactive and non-interactive shells.
<p>
If there is a command name, execution will continue as described in
<xref href=cmdsea><a href="#tag_001_009_001_001">
Command Search and Execution
</a></xref>.
If there is no command name, but the command contained a
command substitution, the
command will complete with the exit status of the last
command substitution performed.
Otherwise, the command will complete with a zero exit status.
<p>
The following example illustrates both how a variable
assignment without a command name affects the current
execution environment, and how an assignment with
a command name only affects the execution environment
of the command.
<pre>
<code>
<b>$</b> x=red
<b>$</b> echo $x
<b>red
$</b> export x
<b>$</b> sh -c 'echo $x'
<b>red
$</b> x=blue sh -c 'echo $x'
<b>blue
$</b> echo $x
<b>red
</b></code>
</pre>
<p>
This next example illustrates that redirections without
a command name are still performed.
<pre>
<code>
<b>$</b> ls foo
<b>ls: foo: no such file or directory
$</b> &gt; foo
<b>$</b> ls foo
<b>foo
</b></code>
</pre>
<p>
A command without a command name,
but one that includes a command substitution, has an
exit status of the last command substitution that the shell performed.
For example:
<pre>
<code>
if      x=$(<i>command</i>)
then    ...
fi
</code>
</pre>
<p>
An example of redirections without a command name
being performed in a subshell shows that the here-document
does not disrupt the standard input of the
<b>while</b>
loop:
<pre>
<code>
IFS=:
while    read a b
do       echo $a
         &lt;&lt;-eof
         Hello
         eof
done &lt;/etc/passwd
</code>
</pre>
<p>
Some examples of commands without command names in AND-OR lists:
<pre>
<code>
&gt; foo || {
    echo "error: foo cannot be created" &gt;&amp;2
    exit 1
}

# set saved if /vmunix.save exists
test -f /vmunix.save &amp;&amp; saved=1
</code>
</pre>
<p>
Command substitution and redirections without command names
both occur in subshells, but they are not
necessarily
the same ones.
For example, in:
<pre>
<code>
exec 3&gt; file
var=$(echo foo &gt;&amp;3) 3&gt;&amp;1
</code>
</pre>
it is unspecified whether
<b>foo</b>
will be echoed to the file or to standard output.
<h5><a name = "tag_001_009_001_001">&nbsp;</a>Command Search and Execution</h5>
<xref type="5" name="cmdsea"></xref>
If a simple command results in a command name and an
optional list of arguments, the following actions will be performed.
<ol>
<p>
<li>
If the command name does not contain any slashes,
the first successful step in the following sequence will occur:
<ol type = a>
<p>
<li>
If the command name matches the name of a
special built-in utility, that special built-in
utility will be invoked.
<p>
<li>
If the command name matches the name
of a function known to this shell, the function will be invoked
as described in
<xref href=funccmd><a href="#tag_001_009_005">
Function Definition Command
</a></xref>.
If the implementation has provided a standard utility
in the form of a function, it will not be recognised
at this point.
It will be invoked in conjunction with the path search
in step 1d.
<br>
<p>
<li>
If the command name matches the name of a utility listed in
the following table, that utility will be invoked.
<pre>
<table  bordercolor=#000000 border=1 align=center><tr valign=top><td align=left>alias
<td align=left>false
<td align=left>jobs
<td align=left>true
<tr valign=top><td align=left>bg
<td align=left>fc
<td align=left>kill
<td align=left>umask
<tr valign=top><td align=left>cd
<td align=left>fg
<td align=left>newgrp
<td align=left>unalias
<tr valign=top><td align=left>command
<td align=left>getopts
<td align=left>read
<td align=left>wait
</table>
</pre>
<p>
<li>
Otherwise,
the command will be searched for using the
<i>PATH</i>
environment variable as described in
the <b>XBD</b> specification, <b>Chapter&nbsp;6</b>, <b>Environment Variables</b>:
<ol type = i>
<p>
<li>
If the search is successful:
<p>
<li>
If the system has implemented the utility as
a regular built-in or as a shell function,
it will be invoked at this point in the path search.
<p>
<li>
Otherwise, the shell will execute the utility
in a separate utility environment (see
<xref href=shexenv><a href="#tag_001_012">
Shell Execution Environment
</a></xref>)
with actions equivalent to calling the <b>XSH</b> specification
<i><a href="../xsh/execve.html">execve()</a></i>
function with the
<i>path</i>
argument set to the pathname resulting from the search,
<i>arg0</i>
set to the command name, and the remaining
arguments set to the operands, if any.
<p>
If the
<i><a href="../xsh/execve.html">execve()</a></i>
function fails due to an error equivalent to the <b>XSH</b> specification error
[ENOEXEC],
the shell will execute a command equivalent to having
a shell invoked with the command name as its
first operand, along with any remaining arguments passed along.
If the executable file is not a text file,
the shell may bypass this command execution,
write an error message, and return an exit status of
126.
<p>
</ol>
<p>
Once a utility has been searched for and found
(either as a result of this specific search or as
part of an unspecified shell startup activity),
an implementation may remember its location and need not
search for the utility again unless the
<i>PATH</i>
variable has been the subject of an assignment.
If the remembered location fails for
a subsequent invocation, the shell will repeat the
search to find the new location for the utility, if any.
<p>
<li>
If the search is unsuccessful, the command will fail with
an exit status
of 127 and the shell will write an error message.
<p>
</ol>
<p>
</ol>
<p>
<li>
If the command name contains at least one slash,
the shell will execute the utility
in a separate utility environment
with actions equivalent to calling the <b>XSH</b> specification
<i><a href="../xsh/execve.html">execve()</a></i>
function with the
<i>path</i>
and
<i>arg0</i>
arguments set to the command name, and the remaining
arguments set to the operands, if any.
<p>
If the
<i><a href="../xsh/execve.html">execve()</a></i>
function fails due to an error equivalent to the <b>XSH</b> specification error
[ENOEXEC],
the shell will execute a command equivalent to having
a shell invoked with the command name as its
first operand, along with any remaining arguments passed along.
If the executable file is not a text file,
the shell may bypass this command execution,
write an error message and return an exit status of
126.
<p>
</>
<p>
This description requires that the shell can execute
shell scripts directly, even if the underlying system
does not support the common
#!
interpreter convention.
That is, if file
<b>foo</b>
contains shell commands and is
executable, the following will execute
<b>foo</b>:
<pre>
<code>
   ./foo
</code>
</pre>
<p>
The sequence selected for the ISO/IEC 9945-2:1993 standard acknowledges that special built-ins
cannot be overridden, but gives the programmer full control over
which versions of other utilities are executed.
It provides a means of suppressing function lookup (via the
<i><a href="command.html">command</a></i>
utility)
for the user's own functions
and ensures that any regular built-ins or functions provided
by the implementation are under the control of the path search.
The mechanisms for associating built-ins or functions with
executable files in the path are not specified by this specification,
but the wording requires that if either is implemented,
the application will not be able to distinguish a function or
built-in from an executable (other than in terms of performance, presumably).
The implementation will ensure that all effects specified
by this specification resulting from the invocation of
the regular built-in or function (interaction with the environment,
variables, traps, and so on) are identical to those resulting from
the invocation of an executable file.
<p>
<b>Example</b>:
Consider three versions of the
<i><a href="ls.html">ls</a></i>
utility:
<ol>
<p>
<li>
The application includes a shell function named
<i><a href="ls.html">ls</a></i>.
<p>
<li>
The user writes a utility named
<i><a href="ls.html">ls</a></i>
and puts it in
<b>/fred/bin</b>.
<p>
<li>
The example implementation provides
<i><a href="ls.html">ls</a></i>
as a regular shell built-in that will be invoked
(either by the shell or directly by
<i>exec</i>
when the path search reaches the directory
<b>/posix/bin</b>.
<p>
</ol>
<p>
If
PATH=/posix/bin,
various invocations yield different versions of
<i><a href="ls.html">ls</a></i>:
<p><table  bordercolor=#000000 border=1 align=center><tr valign=top><th align=center><b>Invocation</b>
<th align=center><b>Version of ls</b>
<tr valign=top><td align=left>ls (from within application script)
<td align=left>(1) function
<tr valign=top><td align=left>command ls (from within application script)
<td align=left>(3) built-in
<tr valign=top><td align=left>ls (from within makefile called by application)
<td align=left>(3) built-in
<tr valign=top><td align=left>system("ls")
<td align=left>(3) built-in
<tr valign=top><td align=left>PATH="/fred/bin:$PATH" ls
<td align=left>(2) user's version
</table>
<h4><a name = "tag_001_009_002">&nbsp;</a>Pipelines</h4>
<xref type="3" name="pipel"></xref>
A
<i>pipeline</i>
is a sequence of one or more
commands separated by the control operator "|".
The standard output of all but the last command
will be connected
to the standard input of the next command.
<p>
The format for a pipeline is:
<pre>
<code>
<b>[</b>!<b>] </b><i>command1 </i><b>[</b> | <i>command2</i> ...<b>]</b>
</code>
</pre>
<p>
The standard output of
<i>command1</i>
will be connected to the standard input of
<i>command2</i>.
The standard input, standard output or both of a command
will be considered to be assigned by the pipeline before any
redirection specified by redirection operators that are part
of the command (see
<xref href=redir><a href="#tag_001_007">
Redirection
</a></xref>).
<p>
If the pipeline is not in the background (see
<xref href=asyncl><a href="#tag_001_009_003">
Lists
</a></xref>),
the shell will wait for the last command specified in the pipeline
to complete, and may also wait for all commands to complete.
<h5><a name = "tag_001_009_002_001">&nbsp;</a>Exit Status</h5>
If the reserved word
"!"
does not precede the pipeline,
the exit status will be the exit status of the last command
specified in the pipeline.
Otherwise, the exit status is the logical NOT
of the exit status of the last command.
That is, if
the last command returns zero, the exit status
will be 1;
if the last command returns greater than zero, the exit status
will be zero.
<p>
Because pipeline assignment of standard input or
standard output or both takes place before redirection, it
can be modified by redirection.
For example:
<pre>
<code>
<b>$ </b><i>command1</i> 2&gt;&amp;1 | <i>command2</i>
</code>
</pre>
sends both the standard output and standard error
of <i>command1</i> to the standard input of <i>command2</i>.
<p>
The reserved word
<b>!</b>
allows more flexible testing using AND and OR lists.
<h4><a name = "tag_001_009_003">&nbsp;</a>Lists</h4>
<xref type="3" name="lists"></xref>
An
<i>AND-OR-list</i>
is a sequence of one or more pipelines separated
by the operators:
<pre>
<code>
&amp;&amp;    ||
</code>
</pre>
<p>
A
<i>list</i>
is a sequence of one or more AND-OR-lists separated by
the operators:
<pre>
<code>
;    &amp;
</code>
</pre>
<p>
and optionally terminated by:
<pre>
<code>
;    &amp;    &lt;newline&gt;
</code>
</pre>
<p>
<br>
The operators
&amp;&amp;
and
||
have equal precedence
and will be evaluated from beginning to end.
For example, both of the following commands write solely
<b>bar</b>
to standard output:
<pre>
<code>
false &amp;&amp; echo foo || echo bar
true || echo foo &amp;&amp; echo bar
</code>
</pre>
<p>
A ";" or newline character
terminator will cause the preceding AND-OR-list to
be executed sequentially; an "&amp;"
will cause asynchronous execution of
the preceding AND-OR-list.
<p>
The term
<i>compound-list</i>
is derived from the grammar in
<xref href=shgram><a href="#tag_001_010">
Shell Grammar
</a></xref>;
it is equivalent to a
sequence of
<i>lists,</i>
separated by
newline characters,
that can be preceded or followed by an arbitrary number of
newline characters.
<p>
The following is an example that illustrates
newline characters
in compound-lists:
<pre>
<code>
while
    # a couple of newlines

    # a list
    date &amp;&amp; who || ls; cat file
    # a couple of newlines

    # another list
    wc file &gt; output &amp; true

do
    # 2 lists
    ls
    cat file
done
</code>
</pre>
<h5><a name = "tag_001_009_003_001">&nbsp;</a>Asynchronous Lists</h5>
<xref type="3" name="asyncl"></xref>
If a command is terminated by the control operator ampersand
(&amp;),
the shell will execute the command asynchronously in a subshell.
This means that the shell does not wait for the command to finish before
executing the next command.
<p>
The format for running a command in the background is:
<pre>
<code>
<i>command1</i> &amp; <b>[</b><i>command2 </i>&amp; ...<b>]
</b></code>
</pre>
<p>
The standard input for an asynchronous list,
before any explicit redirections are performed,
will be considered to be assigned to a file
that has the same properties as
<b>/dev/null</b>.
If it is an interactive shell, this need not happen.
In all cases,
explicit redirection of standard input will override this activity.
<p>
Since the connection of the input to the equivalent of
<b>/dev/null</b>.
is considered to occur before redirections,
the following script would produce no output:
<pre>
<code>
exec &lt; /etc/passwd
cat &lt;&amp;0 &amp;
wait
</code>
</pre>
<p>
When an element of an asynchronous list
(the portion of the list ended by an ampersand,
such as
<i>command1</i>,
above) is started by the shell,
the process ID of the last command in the asynchronous list element
will become known in the current shell execution environment; see
<xref href=shexenv><a href="#tag_001_012">
Shell Execution Environment
</a></xref>.
This process ID will remain known until:
<ol>
<p>
<li>
The command terminates and the application waits for the process ID.
<p>
<li>
Another asynchronous list invoked before
$!
(corresponding to the previous asynchronous list) is expanded in
the current execution environment.
<p>
</ol>
<p>
The implementation need not retain more than the
{CHILD_MAX}
most recent entries in its list of known process IDs
in the current shell execution environment.
<p>
<b>Exit Status</b>:
The exit status of an asynchronous list is zero.
<h5><a name = "tag_001_009_003_002">&nbsp;</a>Sequential Lists</h5>
Commands that are separated by a semicolon
(;)
will be executed sequentially.
<p>
The format for executing commands sequentially is:
<pre>
<code>
<i>command1 </i><b>[</b>; <i>command2</i><b>]</b> ...
</code>
</pre>
<p>
Each command will be expanded and executed in the order specified.
<p>
<b>Exit Status</b>:
The exit status of a sequential list will be the exit status of
the last command in the list.
<h5><a name = "tag_001_009_003_003">&nbsp;</a>AND Lists</h5>
The control operator
&amp;&amp;
denotes an AND list.
The format is:
<pre>
<code>
<i>command1 </i><b>[</b> &amp;&amp; <i>command2</i><b>]</b> ...
</code>
</pre>
<p>
First
<i>command1</i>
will be executed.
If its exit status is zero,
<i>command2</i>
will be executed, and so on until a command has a non-zero
exit status or there are no more commands left to execute.
The commands will be expanded only if they are executed.
<p>
<b>Exit Status</b>:
The exit status of an AND list
will be the exit status of the last command that is executed in the list.
<h5><a name = "tag_001_009_003_004">&nbsp;</a>OR Lists</h5>
The control operator
||
denotes an
OR List.
The format is:
<pre>
<code>
<i>command1 </i><b>[</b> || <i>command2</i><b>]</b> ...
</code>
</pre>
<p>
First,
<i>command1</i>
will be executed.
If its exit status is non-zero,
<i>command2</i>
will be executed, and so on until a command has a zero
exit status or there are no more commands left to execute.
<p>
<b>Exit Status</b>:
The exit status of an
OR list
will be the exit status of the last command that is executed in the list.
<h4><a name = "tag_001_009_004">&nbsp;</a>Compound Commands</h4>
<xref type="3" name="compcmd"></xref>
The shell has several programming constructs that are
<i>compound commands</i>,
which provide control flow for commands.
Each of these compound commands has a reserved word
or control operator at the beginning,
and a corresponding terminator reserved word
or operator at the end.
In addition, each can be followed by redirections
on the same line as the terminator.
Each redirection will apply to all the commands within
the compound command that do not explicitly override
that redirection.
<h5><a name = "tag_001_009_004_001">&nbsp;</a>Grouping Commands</h5>
<xref type="3" name="grpcmd"></xref>
The format for grouping commands is as follows:
<dl compact>

<dt>(<i>compound-list</i>)<dd>Execute
<i>compound-list</i>
in a subshell environment; see
<xref href=shexenv><a href="#tag_001_012">
Shell Execution Environment
</a></xref>.
Variable assignments and built-in commands that
affect the environment will not remain in effect after the
list finishes.

<dt>{ <i>compound-list</i>;}<dd>Execute
<i>compound-list</i>
in the current process environment.
The semicolon shown here
is an example of a control operator
delimiting the
"}"
reserved word.
Other delimiters are possible, as shown in
<xref href=shgram><a href="#tag_001_010">
Shell Grammar
</a></xref>;
a newline character
is frequently used.

</dl>
<p>
<b>Exit Status</b>:
The exit status of a grouping command will be the exit status of
<i>list</i>.
<h5><a name = "tag_001_009_004_002">&nbsp;</a>For Loop</h5>
The
<b>for</b>
loop will execute a sequence of commands for each member in a list of
<i>items</i>.
The
<b>for</b>
loop requires that the reserved words
<b>do</b>
and
<b>done</b>
be used to delimit the sequence of commands.
<p>
The format for the
<b>for</b>
loop is as follows:
<pre>
<code>
for <i>name</i> <b>[</b> in <i>word</i> ... <b>]</b>
do
    <i>compound-list</i>
done
</code>
</pre>
First, the list of words following
<b>in</b>
will be expanded to
generate a list of items.
Then, the variable
<i>name</i>
will be set to each item, in turn, and the
<i>compound-list</i>
executed each time.
If no items result from the expansion,
the
<i>compound-list</i>
will not be executed.
Omitting:
<pre>
<code>
in <i>word</i> ...
</code>
</pre>
is equivalent to:
<pre>
<code>
in "$@"
</code>
</pre>
<p>
The format is shown with generous usage of
newline characters.
See the grammar in
<xref href=shgram><a href="#tag_001_010">
Shell Grammar
</a></xref>
for a precise description of where newline characters
and semicolons can be interchanged.
<p>
<b>Exit Status</b>:
The exit status of a
<b>for</b>
command will be the exit status of the last command that executes.
If there are no items, the exit status will be zero.
<h5><a name = "tag_001_009_004_003">&nbsp;</a>Case Conditional Construct</h5>
The conditional construct
<b>case</b>
will execute the
<i>compound-list</i>
corresponding to the first
one of several
<i>patterns</i>
(see
<xref href=patmat><a href="#tag_001_013">
Pattern Matching Notation
</a></xref>)
that is matched by the string resulting from
the tilde expansion, parameter expansion, command substitution, and
arithmetic expansion and quote removal of the given word.
The reserved word
<b>in</b>
will denote the beginning of the patterns to be matched.
Multiple patterns with the same <i>compound-list</i> are delimited
by the "|" symbol.
The control operator ")"
terminates a list of patterns corresponding to a given action.
The <i>compound-list</i> for each
list of patterns is terminated with
;;.
The
<b>case</b>
construct terminates with the reserved word <b>esac</b> (<b>case</b> reversed).
<p>
The format for the
<b>case</b>
construct is
as follows:
<pre>
<code>
case <i>word</i> in
    <b>[</b>(<b>]</b><i>pattern1</i>)                 <i>compound-list</i>;;
    <b>[</b>(<b>]</b><i>pattern2</i>|<i>pattern3</i>)        <i>compound-list</i>;;
    ...
esac
</code>
</pre>
<p>
The
;;
is optional for the last
<i>compound-list</i>.
<p>
In order from the beginning to the end of the
<b>case</b>
statement, each
<i>pattern</i>
that labels a
<i>compound-list</i>
is subjected
to tilde expansion, parameter expansion,
command substitution and arithmetic expansion,
and the result of these expansions is compared
against the expansion of
<i>word</i>,
according to the rules described in
<xref href=patmat><a href="#tag_001_013">
Pattern Matching Notation
</a></xref>
(which also describes the
effect of quoting parts of the pattern).
After the first match, no
more patterns are expanded, and the
<i>compound-list</i>
is executed.
The order of expansion and comparison of multiple
<i>pattern</i>s
that label a
<i>compound-list</i>
statement is unspecified.
<p>
<b>Exit Status</b>:
The exit status of
<b>case</b>
is zero if no patterns are matched.
Otherwise, the exit status will be the exit status of the
last command executed in the
<i>compound-list</i>.
<p>
The pattern
*,
given as the last pattern in a
<b>case</b>
construct,
is equivalent to the default case in
a C-language <b>switch</b> statement.
<p>
The grammar shows that reserved words can be used
as patterns, even if one is the first word on a line.
Obviously, the reserved word <b>esac</b> cannot be used in this manner.
<h5><a name = "tag_001_009_004_004">&nbsp;</a>If Conditional Construct</h5>
The
<b>if</b>
command will execute a
<i>compound-list</i>
and use its exit status to determine whether to execute another
<i>compound-list</i>.
<p>
The format for the
<b>if</b>
construct is as follows:
<pre>
<code>
if <i>compound-list
</i>then
       <i>compound-list
</i><b>[</b>elif <i>compound-list
</i>then
       <i>compound-list</i><b>]</b> ...
<b>[</b>else
       <i>compound-list</i><b>]</b>
fi
</code>
</pre>
<p>
The
<b>if</b>
<i>compound-list</i>
is executed; if its exit status is
zero, the
<b>then</b>
<i>compound-list</i>
is executed and the command will complete.
Otherwise, each
<b>elif</b>
<i>compound-list</i>
is executed, in turn, and if its exit status is zero, the
<i>then</i>
<i>compound-list</i>
is executed and the command will complete.
Otherwise, the
<b>else</b>
<i>compound-list</i>
is executed.
<p>
<b>Exit Status</b>:
The exit status of the
<b>if</b>
command will be the exit status of the
<i>then</i>
or
<b>else</b>
<i>compound-list</i>
that was executed, or zero, if none was executed.
<h5><a name = "tag_001_009_004_005">&nbsp;</a>While Loop</h5>
The
<b>while</b>
loop continuously will execute one
<i>compound-list</i>
as long as another
<i>compound-list</i>
has a zero exit status.
<p>
The format of the
<b>while</b>
loop is as follows:
<pre>
<code>
while <i>compound-list-1
</i>do
       <i>compound-list-2
</i>done
</code>
</pre>
<p>
The
<i>compound-list-1</i>
will be executed, and if it has a non-zero exit status, the
<b>while</b>
command will complete.
Otherwise, the
<i>compound-list-2</i>
will be executed, and the process will repeat.
<p>
<b>Exit Status</b>:
The exit status of the
<b>while</b>
loop will be the exit status of the last
<i>compound-list-2</i>
executed, or zero if none was executed.
<h5><a name = "tag_001_009_004_006">&nbsp;</a>Until Loop</h5>
The
<b>until</b>
loop continuously will execute one
<i>compound-list</i>
as long as another
<i>compound-list</i>
has a non-zero exit status.
<p>
The format of the
<b>until</b>
loop is as follows:
<pre>
<code>
until <i>compound-list-1
</i>do
       <i>compound-list-2
</i>done
</code>
</pre>
<p>
The
<i>compound-list-1</i>
will be executed, and if it has a zero exit status, the
<b>until</b>
command will complete.
Otherwise, the
<i>compound-list-2</i>
will be executed, and the process will repeat.
<p>
<b>Exit Status</b>:
The exit status of the
<b>until</b>
loop will be the exit status of the last
<i>compound-list-2</i>
executed, or zero if none was executed.
<h4><a name = "tag_001_009_005">&nbsp;</a>Function Definition Command</h4>
<xref type="3" name="funccmd"></xref>
A function is a user-defined name that is used as a simple command
to call a compound command with new positional parameters.
A function is defined with a
<i>function definition command</i>.
<p>
The format of a function definition command is as follows:
<pre>
<code>
<i>fname</i>() <i>compound-command</i><b>[</b><i>io-redirect</i> ...<b>]
</b></code>
</pre>
The function is named
<i>fname</i>;
it must be a name (see <b>name</b> in the <b>XBD</b> specification, <a href="../xbd/glossary.html"><b>Glossary</b>&nbsp;</a> ).
An implementation may allow other characters
in a function name as an extension.
The implementation will maintain separate name spaces
for functions and variables.
<p>
The
()
in the function definition command consists of two operators.
Therefore, intermixing
blank characters
with the
<i>fname</i>,
"("
and
")"
is allowed, but unnecessary.
<p>
The argument
<i>compound-command</i>
represents a compound command, as described in
<xref href=compcmd><a href="#tag_001_009_004">
Compound Commands
</a></xref>.
<p>
When the function is declared, none of the expansions in
<xref href=wordexp><a href="#tag_001_006">
Word Expansions
</a></xref>
will be performed on the text in
<i>compound-command</i>
or
<i>io-redirect</i>;
all expansions will be performed as normal each time the
function is called.
Similarly, the optional
<i>io-redirect</i>
redirections and any variable assignments within
<i>compound-command</i>
will be performed during the execution
of the function itself, not the function definition.
See
<xref href=sherr><a href="#tag_001_008_001">
Consequences of Shell Errors
</a></xref>
for the consequences of failures of these operations on
interactive and non-interactive shells.
<p>
When a function is executed, it will have the
syntax-error and variable-assignment properties
described for special built-in utilities
in the enumerated list at the beginning of
<xref href=sbi><a href="#tag_001_014">
Special Built-in Utilities
</a></xref>.
<p>
The
<i>compound-command</i>
will be executed whenever the function name is
specified as the name of a simple command (see
<xref href=cmdsea><a href="#tag_001_009_001_001">
Command Search and Execution
</a></xref>).
The operands to the command temporarily
will become the positional parameters during the execution of the
<i>compound-command</i>;
the special parameter
"#"
will also be changed to reflect
the number of operands.
The special parameter
0
will be unchanged.
When the function completes, the values of the positional parameters and
the special parameter
"#"
will be restored to the values they had before the function was executed.
If the special built-in
<i><a href="chap2.html#tag_001_014_010">return</a></i>
is executed in the
<i>compound-command</i>,
the function will complete and
execution will resume with the next command after the function
call.
<p>
An example of how a function definition can be used
wherever a simple command is allowed:
<pre>
<code>
# If variable i is equal to "yes",
# define function foo to be ls -l
#
[ "$i" = yes ] &amp;&amp; foo() {
    ls -l
}
</code>
</pre>
<h5><a name = "tag_001_009_005_001">&nbsp;</a>Exit Status</h5>
The exit status of a function definition will be zero
if the function was declared successfully;
otherwise, it will be greater than zero.
The exit status of a function invocation will be the exit status of
the last command executed by the function.
<hr size=2 noshade>
<h3><a name = "tag_001_010">&nbsp;</a>Shell Grammar</h3>
<xref type="2" name="shgram"></xref>
The following grammar
defines the Shell Command Language.
This formal syntax takes precedence over
the preceding text syntax description.
<h4><a name = "tag_001_010_001">&nbsp;</a>Shell Grammar Lexical Conventions</h4>
The input language to the shell must be first recognised at the
character level.
The resulting tokens will be classified by their
immediate context according to the following rules (applied in order).
These rules are used to determine what a &quot;token&quot; that is
subject to parsing at the token level is.
The rules for token recognition in
<xref href=token><a href="#tag_001_003">
Token Recognition
</a></xref>
will apply.
<ol>
<p>
<li>
A newline character will be returned as the token identifier
<b>NEWLINE</b>.
<p>
<li>
If the token is an operator, the token identifier for that
operator will result.
<p>
<li>
If the string consists solely of digits and the delimiter character
is one of &lt; or &gt;, the token identifier
<b>IO_NUMBER</b>
will be returned.
<p>
<li>
Otherwise, the token identifier
<b>TOKEN</b>
will result.
<p>
</ol>
<p>
Further distinction on
<b>TOKEN</b>
is context-dependent.
It may be that the same
<b>TOKEN</b>
yields
<b>WORD</b>,
a
<b>NAME</b>,
an
<b>ASSIGNMENT</b>,
or one of the reserved words below, dependent upon the context.
Some of the productions in the grammar below are
annotated with a rule number from the following list.
When a
<b>TOKEN</b>
is seen where one of those annotated productions could be used to reduce
the symbol, the applicable rule will be applied
to convert the token identifier type of the
<b>TOKEN</b>
to a token identifier acceptable at that point in the grammar.
The reduction will then proceed based upon the
token identifier type yielded by the rule applied.
When more than one rule
applies, the highest numbered rule will apply (which in turn may
refer to another rule).
(Note that except in rule 7,
the presence of an = in the token has no effect.)
<p>
The
<b>WORD</b>
tokens will have the word expansion rules applied to them
immediately before the associated command is executed, not at the time
the command is parsed.
<h4><a name = "tag_001_010_002">&nbsp;</a>Shell Grammar Rules</h4>
<xref type="3" name="shgramr"></xref>
<ol>
<p>
<li>
[Command Name]
<br>
When the
<b>TOKEN</b>
is exactly a reserved word, the token identifier for that
reserved word will result.
Otherwise, the token
<b>WORD</b>
will be returned.
Also, if the parser is in any state where only a reserved word
could be the next correct token, proceed as above.
This rule applies rather narrowly:
when a compound list is terminated by some clear delimiter (such as
the closing
<b>fi</b>
of an inner
<b>if_clause</b>)
then it would apply;
where the compound list might continue (as in after a ;), rule
7a (and consequently the first sentence of this rule) would apply.
In many instances the
two conditions are identical, but this part of this
rule does not give licence to treating a
<b>WORD</b>
as a reserved word unless it is in a place where a
reserved word must appear.
<dl><dt><b>Note:</b>
<dd>Because at this point quote marks are retained in the token,
quoted strings cannot be recognised as reserved words.
This rule also implies that reserved
words will not be recognised except in certain
positions in the input, such as after a
newline character
or semicolon; the grammar presumes that if the reserved word is
intended, it will be properly delimited by the user, and does
not attempt to reflect that requirement directly.
Also note that line joining is done before tokenisation,
as described in
<xref href=esc><a href="#tag_001_002_001">
Escape Character (Backslash)
</a></xref>,
so escaped newlines are already removed at this point.
</dl>
<p>
Rule 1 is not directly referenced in the grammar, but
is referred to by other rules, or applies globally.
<p>
<li>
[Redirection to or from filename]
<br>
The expansions specified in
<xref href=redir><a href="#tag_001_007">
Redirection
</a></xref>
will occur.
As specified there, exactly one
field can result (or the result is unspecified), and there
are additional requirements on pathname expansion.
<p>
<li>
[Redirection from here-document]
<br>
Quote removal
will be applied to the word to determine the delimiter that
will be used to find the end of the here-document that
begins after the next
newline character.
<p>
<li>
[Case statement termination]
<br>
When the
<b>TOKEN</b>
is exactly the
reserved word
<b>Esac</b>,
the token identifier for
<b>Esac</b>
will result.
Otherwise, the token
<b>WORD</b>
will be returned.
<p>
<li>
[NAME
in
<b>for</b>]
<br>
When the
<b>TOKEN</b>
meets the requirements for a name
(see <b>name</b> in the <b>XBD</b> specification, <a href="../xbd/glossary.html"><b>Glossary</b>&nbsp;</a> ),
the token identifier
<b>NAME</b>
will result.
Otherwise, the token
<b>WORD</b>
will be returned.
<p>
<li>
[Third word of
<b>for</b>
and
<b>case</b>]
<br>
When the
<b>TOKEN</b>
is exactly the
reserved word
<b>In</b>,
the token identifier for
<b>In</b>
will result.
Otherwise, the token
<b>WORD</b>
will be returned.
(As indicated in the grammar, a
<b>linebreak</b>
precedes the token
<b>In</b>.
If newline characters are present at the indicated location, it is
the token after them that is treated in this fashion.)
<p>
<li>
[Assignment preceding command name]
<ol type = a>
<p>
<li>
[When the first word]
<br>
If the
<b>TOKEN</b>
does not contain the character
"=",
rule 1 will be applied.
Otherwise, 7b will be applied.
<p>
<li>
[Not the first word]
<br>
If the
<b>TOKEN</b>
contains the equal sign character:
<ul>
<p>
<li>
If it begins with =,
the token
<b>WORD</b>
will be returned.
<p>
<li>
If all the characters preceding = form a valid name
(see
<b>name</b>
in the <b>XSH</b> specification),
the token
<b>ASSIGNMENT_WORD</b>
will be returned.
(Quoted characters cannot participate in forming a valid name.)
<p>
<li>
Otherwise, it is unspecified whether it is
<b>ASSIGNMENT_WORD</b>
or
<b>WORD</b>
that is returned.
<p>
</ul>
<p>
</ol>
<p>
Assignment to the
<b>NAME</b>
will occur as specified in
<xref href=simpcmd><a href="#tag_001_009_001">
Simple Commands
</a></xref>.
<p>
<li>
[NAME
in function]
<br>
When the
<b>TOKEN</b>
is exactly a reserved word, the
token identifier for that reserved word will result.
Otherwise, when the
<b>TOKEN</b>
meets the requirements for a name
(see
<b>Name</b>),
the token identifier
<b>NAME</b>
will result.
Otherwise, rule 7 will apply.
<p>
<li>
[Body of function]
<br>
Word expansion and assignment will never occur,
even when required by the rules above, when this rule is being parsed.
Each
<b>TOKEN</b>
that might either be expanded or have
assignment applied to it will instead be returned as a single
<b>WORD</b>
consisting only of characters that are exactly the token described in
<xref href=token><a href="#tag_001_003">
Token Recognition
</a></xref>.
<p>
</ol>
<br>
<pre>
<code>
/* -------------------------------------------------------
   The grammar symbols
   ------------------------------------------------------- */

%token  WORD
%token  ASSIGNMENT_WORD
%token  NAME
%token  NEWLINE
%token  IO_NUMBER

/* The following are the operators mentioned above. */

%token  AND_IF    OR_IF    DSEMI
/*      '&amp;&amp;'      '||'     ';;'    */

%token  DLESS  DGREAT  LESSAND  GREATAND  LESSGREAT  DLESSDASH
/*      '&lt;&lt;'   '&gt;&gt;'    '&lt;&amp;'     '&gt;&amp;'      '&lt;&gt;'       '&lt;&lt;-'   */

%token  CLOBBER
/*      '&gt;|'   */

/* The following are the reserved words. */

%token  If    Then    Else    Elif    Fi    Do    Done
/*      'if'  'then'  'else'  'elif'  'fi'  'do'  'done'   */

%token  Case    Esac    While    Until    For
/*      'case'  'esac'  'while'  'until'  'for'   */

/* These are reserved words, not operator tokens, and are
   recognised when reserved words are recognised. */

%token  Lbrace    Rbrace    Bang
/*      '{'       '}'       '!'   */

%token  In
/*      'in'   */

/* -------------------------------------------------------
   The Grammar
   ------------------------------------------------------- */

%start  complete_command
%%
complete_command : list separator
                 | list
                 ;
list             : list separator_op and_or
                 |                   and_or
                 ;
and_or           :                         pipeline
                 | and_or AND_IF linebreak pipeline
                 | and_or OR_IF  linebreak pipeline
                 ;
pipeline         :      pipe_sequence
                 | Bang pipe_sequence
                 ;
pipe_sequence    :                             command
                 | pipe_sequence '|' linebreak command
                 ;
command          : simple_command
                 | compound_command
                 | compound_command redirect_list
                 | function_definition
                 ;
compound_command : brace_group
                 | subshell
                 | for_clause
                 | case_clause
                 | if_clause
                 | while_clause
                 | until_clause
                 ;
subshell         : '(' compound_list ')'
                 ;
compound_list    :              term
                 | newline_list term
                 |              term separator
                 | newline_list term separator
                 ;
term             : term separator and_or
                 |                and_or
                 ;
for_clause       : For name linebreak                            do_group
                 | For name linebreak in wordlist sequential_sep do_group
                 ;
name             : NAME                     /* Apply rule 5 */
                 ;
in               : In                       /* Apply rule 6 */
                 ;
wordlist         : wordlist WORD
                 |          WORD
                 ;
case_clause      : Case WORD linebreak in linebreak case_list Esac
                 | Case WORD linebreak in linebreak           Esac
                 ;
case_list        : case_list case_item
                 |              case_item
                 ;
case_item        :     pattern ')' linebreak     DSEMI linebreak
                 |     pattern ')' compound_list DSEMI linebreak
                 | '(' pattern ')' linebreak     DSEMI linebreak
                 | '(' pattern ')' compound_list DSEMI linebreak
                 ;
pattern          :             WORD         /* Apply rule 4 */
                 | pattern '|' WORD     /* Do not apply rule (4) */
                 ;
if_clause        : If compound_list Then compound_list else_part Fi
                 | If compound_list Then compound_list           Fi
                 ;
else_part        : Elif compound_list Then else_part
                 | Else compound_list
                 ;
while_clause     : While compound_list do_group
                 ;
until_clause     : Until compound_list do_group
                 ;
function_definition : fname '(' ')' linebreak function_body
                 ;
function_body    : compound_command                /* Apply rule 9 */
                 | compound_command redirect_list  /* Apply rule 9 */
                 ;
fname            : NAME                            /* Apply rule 8 */
                 ;
brace_group      : Lbrace compound_list Rbrace
                 ;
do_group         : Do compound_list Done
                 ;
simple_command   : cmd_prefix cmd_word cmd_suffix
                 | cmd_prefix cmd_word
                 | cmd_prefix
                 | cmd_name cmd_suffix
                 | cmd_name
                 ;
cmd_name         : WORD                   /* Apply rule 7a */
                 ;
cmd_word         : WORD                   /* Apply rule 7b */
                 ;
cmd_prefix       :            io_redirect
                 | cmd_prefix io_redirect
                 |            ASSIGNMENT_WORD
                 | cmd_prefix ASSIGNMENT_WORD
                 ;
cmd_suffix       :            io_redirect
                 | cmd_suffix io_redirect
                 |            WORD
                 | cmd_suffix WORD
                 ;
redirect_list    :               io_redirect
                 | redirect_list io_redirect
                 ;
io_redirect      :           io_file
                 | IO_NUMBER io_file
                 |           io_here
                 | IO_NUMBER io_here
                 ;
io_file          : '&lt;'       filename
                 | LESSAND   filename
                 | '&gt;'       filename
                 | GREATAND  filename
                 | DGREAT    filename
                 | LESSGREAT filename
                 | CLOBBER   filename
                 ;
filename         : WORD                      /* Apply rule 2 */
                 ;
io_here          :    DLESS     here_end
                 |    DLESSDASH here_end
                 ;
here_end         : WORD                      /* Apply rule 3 */
                 ;
newline_list     :              NEWLINE
                 | newline_list NEWLINE
                 ;
linebreak        : newline_list
                 | /* empty */
                 ;
separator_op     : '&amp;'
                 | ';'
                 ;
separator        : separator_op linebreak
                 | newline_list
                 ;
sequential_sep   : ';' linebreak
                 | newline_list
                 ;
</code>
</pre>
<p>
There are several subtle aspects of this grammar where conventional usage
implies rules about the grammar that in fact are not true.
<p>
For
<b>compound_list</b>,
only the forms that end in a
<b>separator</b>
allow a reserved word to be recognised, so usually only
a
<b>separator</b>
can be
used where a compound list precedes a reserved word (such as
<b>Then</b>,
<b>Else</b>,
<b>Do</b>
and
<b>Rbrace</b>).
Explicitly requiring a separator
would disallow such valid (if rare) statements as:
<pre>
<code>
if (false) then (echo x) else (echo y) fi
</code>
</pre>
<p>
See the Note under special grammar rule 1.
<p>
Note that the bodies of here-documents are handled by token recognition
(see
<xref href=token><a href="#tag_001_003">
Token Recognition
</a></xref>)
and do not appear in the grammar directly.
(However, the here-document I/O
redirection operator is handled as part of the grammar.)
<p>
The start symbol of the grammar
(<b>complete_command</b>)
represents either
input from the command line or a shell script.
It is repeatedly applied
by the interpreter to its input, and represents a single chunk of that
input as seen by the interpreter.
<hr size=2 noshade>
<h3><a name = "tag_001_011">&nbsp;</a>Signals and Error Handling</h3>
When a command is in an asynchronous list, the shell will prevent SIGQUIT
and SIGINT signals from the keyboard from interrupting the command.
Otherwise, signals will have the values inherited
by the shell from its parent (see also the
<i><a href="chap2.html#tag_001_014_014">trap</a></i>
special built-in).
<p>
When a signal for which a trap has been set is received
while the shell is waiting for the completion of a utility
executing a foreground command, the trap associated with
that signal will not be executed until after the foreground
command has completed.
When the shell is waiting, by means of the
<i><a href="wait.html">wait</a></i>
utility, for asynchronous commands to complete,
the reception of a signal for which a trap has been set
will cause the
<i><a href="wait.html">wait</a></i>
utility to return immediately with an exit
status &gt;128, immediately after which the trap associated with
that signal will be taken.
<p>
If multiple signals are pending for the shell for which
there are associated trap actions,
the order of execution of trap actions is unspecified.
<hr size=2 noshade>
<h3><a name = "tag_001_012">&nbsp;</a>Shell Execution Environment</h3>
<xref type="2" name="shexenv"></xref>
A shell execution environment consists of the following:
<ul>
<p>
<li>
open files inherited upon invocation of the shell, plus
open files controlled by
<i>exec</i>
<p>
<li>
working directory as set by
<i><a href="cd.html">cd</a></i>
<p>
<li>
file creation mask set by
<i><a href="umask.html">umask</a></i>
<p>
<li>
current traps set by
<i><a href="chap2.html#tag_001_014_014">trap</a></i>
<p>
<li>
shell parameters that are set by variable assignment (see the
<i>set</i>
special built-in)
or from the <b>XSH</b> specification environment inherited by the shell when it
begins (see the
<i><a href="#tag_001_014_008">export</a></i>
special built-in)
<p>
<li>
shell functions (see
<xref href=funccmd><a href="#tag_001_009_005">
Function Definition Command
</a></xref>)
<p>
<li>
options turned on at invocation or by
<i>set</i>
<p>
<li>
process IDs of the last commands in asynchronous lists
known to this shell environment; see
<xref href=asyncl><a href="#tag_001_009_003">
Lists
</a></xref>
<p>
<li>
shell aliases (see
<xref href=alsub><a href="#tag_001_003_001">
Alias Substitution
</a></xref>).
<p>
</ul>
<p>
Utilities other than the special built-ins (see
<xref href=sbi><a href="#tag_001_014">
Special Built-in Utilities
</a></xref>)
will be invoked in a separate environment that consists of the following.
The initial value of these objects will be the same as that for the parent
shell, except as noted below.
<ul>
<p>
<li>
open files inherited on invocation of the shell, open files
controlled by the
<i><a href="chap2.html#tag_001_014_006">exec</a></i>
special built-in
plus any modifications and additions specified by any redirections
to the utility
<p>
<li>
current working directory
<p>
<li>
file creation mask
<p>
<li>
if the utility is a shell script, traps caught by the shell will be
set to the default values and traps ignored by the shell will be
set to be ignored by the utility; if the utility is not a shell
script, the trap actions (default or ignore) will be mapped into
the appropriate signal handling actions for the utility
<p>
<li>
variables with the
<i>export</i>
attribute,
along with those explicitly exported for the duration of the command,
will be passed to the utility as <b>XSH</b> specification environment variables.
<p>
</ul>
<p>
The environment of the shell process will not be changed by the utility
unless explicitly specified by the utility description (for example,
<i><a href="cd.html">cd</a></i>
and
<i><a href="umask.html">umask</a></i>).
<p>
A subshell environment will be created as a duplicate
of the shell environment,
except that signal traps set by that shell environment
will be set to the default values.
Changes made to the subshell environment will not affect the
shell environment.
Command substitution, commands that are grouped with parentheses
and asynchronous lists will be executed in a subshell environment.
Additionally, each command of a multi-command pipeline
is in a subshell environment; as an extension, however,
any or all commands in a pipeline may be executed in
the current environment.
All other commands will be executed in the current shell environment.
<p>
Some systems have implemented the last stage
of a pipeline in the current environment so that
commands such as:
<pre>
<code>
<i>command</i> | read foo
</code>
</pre>
set variable
<b>foo</b>
in the current environment.
This extension is allowed, but not required;
therefore, a shell programmer should consider a pipeline
to be in a subshell environment, but not depend on it.
<hr size=2 noshade>
<h3><a name = "tag_001_013">&nbsp;</a>Pattern Matching Notation</h3>
<xref type="2" name="patmat"></xref>
The pattern matching notation described in this
section is used to specify patterns for
matching strings in the shell.
Historically, pattern matching notation is related to, but slightly
different from, the regular expression notation described in
the <b>XBD</b> specification, <b>Chapter&nbsp;7</b>, <b>Regular Expressions</b>.
For this reason, the description of the
rules for this pattern matching notation
are based on the description of regular expression notation.
<h4><a name = "tag_001_013_001">&nbsp;</a>Patterns Matching a Single Character</h4>
<xref type="3" name="patmats"></xref>
The following <i>patterns matching a single character</i>
match a single character:
<i>ordinary characters</i>,
<i>special pattern characters</i>
and
<i>pattern bracket expressions</i>.
The pattern bracket expression will also match a single collating element.
<p>
An ordinary character is a pattern that matches itself.
It can be any character in the supported character set except
for NUL, those special shell characters in
<xref href=quoting><a href="#tag_001_002">
Quoting
</a></xref>
that require quoting, and
the following three special pattern characters.
Matching is based on the bit pattern
used for encoding the character,
not on the graphic representation of the character.
If any character (ordinary, shell special or pattern special)
is quoted, that pattern will match the character itself.
The shell special characters always require quoting.
<p>
When unquoted and outside a bracket expression,
the following three characters will have special meaning in the
specification of patterns:
<dl compact>

<dt>?<dd>A question-mark is a pattern that will match any character.

<dt>*<dd>An asterisk is a pattern that
will match multiple characters, as described in
<xref href=patmatm><a href="#tag_001_013_002">
Patterns Matching Multiple Characters
</a></xref>.

<dt>[<dd>The open bracket will introduce a pattern bracket expression.

</dl>
<p>
The description of basic regular expression bracket expressions in
the <b>XBD</b> specification, <b>Section 7.3.5</b>, <b>RE Bracket Expression</b> also applies to the pattern bracket expression, except that
the exclamation-mark character
(!)
replaces the circumflex character
(^)
in its role in a
<i>non-matching list</i>
in the regular expression notation.
A bracket expression starting with an unquoted circumflex character
produces unspecified results.
<p>
The restriction on a circumflex in a bracket expression is
to allow implementations that support pattern matching
using the circumflex as the negation character in addition
to the exclamation-mark.
A portable application must use something like
[\^!]
to match either character.
<p>
When pattern matching is used where shell quote removal
is not performed (such as in the argument to the
<i><a href="find.html">find</a></i>
<b>-name</b>
primary when
<i><a href="find.html">find</a></i>
is being called using one of the <b>XSH</b> specification
<i>exec</i>
functions, or in the
<i>pattern</i>
argument to the
<i><a href="../xsh/fnmatch.html">fnmatch()</a></i>
function), special characters can be escaped to remove
their special meaning by preceding them with a
backslash character.
This escaping
backslash
will be discarded.
The sequence
\\
represents one literal backslash.
All of the requirements and effects of quoting
on ordinary, shell special and special pattern
characters will apply to escaping in this context.
<p>
Both quoting and escaping are described here
because pattern matching must work in three separate circumstances:
<ul>
<p>
<li>
Calling directly upon the shell, such as in pathname expansion or in a
<b>case</b>
statement.
All of the following will match the string or file
<b>abc:</b>
<pre>
<code>
abc  "abc"  a"b"c  a\bc  a[b]c  a["b"]c  a[\b]c  a["\b"]c  a?c  a*c
</code>
</pre>
The following will not:
<pre>
<code>
"a?c"  a\*c  a\[b]c
</code>
</pre>
<p>
<li>
Calling a utility or function without going through a shell,
as described for
<i><a href="find.html">find</a></i>
and the <b>XSH</b> specification function
<i><a href="../xsh/fnmatch.html">fnmatch()</a></i>.
<p>
<li>
Calling utilities such as
<i><a href="find.html">find</a></i>,
<i><a href="cpio.html">cpio</a></i>,
<i><a href="tar.html">tar</a></i>
or
<i><a href="pax.html">pax</a></i>
through the shell command line.
In this case, shell quote removal
is performed before the utility sees the argument.
For example, in:
<pre>
<code>
find /bin -name "e\c[\h]o" -print
</code>
</pre>
after quote removal, the backslashes are presented to
<i><a href="find.html">find</a></i>
and it treats them as escape characters.
Both precede ordinary characters, so the
<b>c</b>
and
<b>h</b>
represent themselves and
<b>echo</b>
would be found on many historical systems (that have it in
<b>/bin</b>).
To find a filename that contained shell special characters
or pattern characters,
both quoting and escaping are required, such as:
<pre>
<code>
pax -r ... "*a\(\?"
</code>
</pre>
to extract a filename ending with
<b>a(?</b>.
<p>
</ul>
<p>
Conforming applications are required
to quote or escape the shell special characters
(sometimes called metacharacters).
If used without this protection, syntax errors
can result or implementation extensions can be triggered.
For example, the KornShell supports a series of
extensions based on parentheses in patterns.
<h4><a name = "tag_001_013_002">&nbsp;</a>Patterns Matching Multiple Characters</h4>
<xref type="3" name="patmatm"></xref>
The following rules are used to construct <i>patterns matching multiple
characters</i> from <i>patterns matching a single character</i>:
<ol>
<p>
<li>
The asterisk (*)
is a pattern that will match any string, including the null string.
<p>
<li>
The concatenation of <i>patterns matching a single character</i>
is a valid pattern that will match the concatenation
of the single characters or collating elements matched
by each of the concatenated patterns.
<p>
<li>
The concatenation of one or more
<i>patterns matching a single character</i>
with one or more asterisks is a valid pattern.
In such patterns, each asterisk
will match a string of zero or more characters,
matching the greatest possible number of characters
that still allows the remainder of the pattern to match the string.
<p>
</ol>
<p>
Since each asterisk matches zero or more occurrences, the patterns
a*b and a**b have identical functionality.
<h5><a name = "tag_001_013_002_001">&nbsp;</a>Examples</h5>
<dl compact>

<dt>a[bc]<dd>matches the strings
<b>ab</b>
and
<b>ac</b>.

<dt>a*d<dd>matches the strings
<b>ad</b>,
<b>abd</b>
and
<b>abcd</b>,
but not the string
<b>abc</b>.

<dt>a*d*<dd>matches the strings
<b>ad</b>,
<b>abcd</b>,
<b>abcdef</b>,
<b>aaaad</b>
and
<b>adddd</b>.

<dt>*a*d<dd>matches the strings
<b>ad</b>,
<b>abcd</b>,
<b>efabcd</b>,
<b>aaaad</b>
and
<b>adddd</b>.

</dl>
<h4><a name = "tag_001_013_003">&nbsp;</a>Patterns Used for Filename Expansion</h4>
<xref type="3" name="patfilx"></xref>
The rules described so far in
<xref href=patmats><a href="#tag_001_013_001">
Patterns Matching a Single Character
</a></xref>
and
<xref href=patmatm><a href="#tag_001_013_002">
Patterns Matching Multiple Characters
</a></xref>
are qualified by the following rules that
apply when pattern matching notation is
used for filename expansion.
<ol>
<p>
<li>
The slash character in a pathname must be explicitly matched
by using one or more slashes in the pattern; it cannot be matched by
the asterisk or question-mark special characters or by a bracket expression.
Slashes in the pattern are identified before bracket expressions;
thus, a slash cannot be included in a pattern bracket expression
used for filename expansion.
For example, the pattern
a[b/c]d will not match such pathnames as
<b>abd</b>
or
<b>a/d</b>.
It will only match a pathname of literally
<b>a[b/c]d</b>.
<p>
<li>
If a filename begins with a period (.)
the period must be explicitly
matched by using a period as the first character of the pattern
or immediately following a slash character.
The leading period will not be matched by:
<ul>
<p>
<li>
the asterisk or question-mark special characters
<p>
<li>
a bracket expression containing a non-matching list, such as:
<pre>
<code>
[!a]
</code>
</pre>
a range expression, such as:
<pre>
<code>
[%-0]
</code>
</pre>
or a character class expression, such as:
<pre>
<code>
[[:punct:]]
</code>
</pre>
<p>
</ul>
<p>
It is unspecified whether an explicit period in a bracket expression
matching list, such as:
<pre>
<code>
[.abc]
</code>
</pre>
can match a leading period in a filename.
<p>
<li>
Specified patterns are matched
against existing filenames and pathnames, as appropriate.
Each component that contains a pattern character
requires read permission in the directory containing that component.
Any component,
except the last, that does not contain a pattern character
requires search permission.
For example, given the pattern:
<pre>
<code>
/foo/bar/x*/bam
</code>
</pre>
search permission is needed for directories <b>/</b> and <b>foo</b>,
search and read permissions are needed for directory <b>bar</b>,
and search permission is needed for each <b>x*</b> directory.
If the pattern matches any existing filenames
or pathnames, the pattern will be replaced with those
filenames and pathnames, sorted according to
the collating sequence in effect in the current locale.
If the pattern
contains an invalid bracket expression or
does not match any existing filenames
or pathnames, the pattern string is left unchanged.
<p>
</ol>
<hr size=2 noshade>
<h3><a name = "tag_001_014">&nbsp;</a>Special Built-in Utilities</h3>
<xref type="2" name="sbi"></xref>
The following
<i>special built-in</i>
utilities will be supported in the shell
command language.
The output of each command,
if any, will be written to standard output,
subject to the normal redirection and piping
possible with all commands.
<p>
The term
<i>built-in</i>
implies that the shell can execute the utility directly
and does not need to search for it.
An implementation can choose to make any utility a built-in;
however, the special built-in utilities described here differ
from regular built-in utilities in
two respects:
<ul>
<p>
<li>
A syntax error in a special built-in utility may cause
a shell executing that utility to abort, while a syntax
error in a regular built-in utility will not cause a
shell executing that utility to abort.
(See
<xref href=sherr><a href="#tag_001_008_001">
Consequences of Shell Errors
</a></xref>
for the consequences of errors on
interactive and non-interactive shells.)
If a special built-in utility encountering a syntax error does not
abort the shell, its exit value will be non-zero.
<p>
<li>
Variable assignments specified with
special built-in utilities will remain
in effect after the built-in completes;
this is not the case with a regular built-in
or other utility.
<p>
</ul>
<p>
The special built-in utilities in this section
need not be provided in a manner accessible via the <b>XSH</b> specification
<i>exec</i>
family of functions.
<p>
Some of the special built-ins are described as
conforming to the <b>XBD</b> specification, <a href="../xbd/utilconv.html#usg"><b>Utility Syntax Guidelines</b>&nbsp;</a> .
For those that are not, the requirement in
<a href="utildes.html">Utility Description Defaults</a>
<xref href=utildes></xref>
that -- be recognised as a first argument to be discarded does
not apply and a portable application must not use that argument.
<hr size=2 noshade>
<h4><a name = "tag_001_014_001">&nbsp;</a>break - Exit From for, while or until Loop</h4>
<h5><a name = "tag_001_014_001_001">&nbsp;</a>SYNOPSIS</h5>
<code>
<i>break</i>
<b>[</b><i>n</i><b>]</b>
</code>
<h5><a name = "tag_001_014_001_002">&nbsp;</a>DESCRIPTION</h5>
Exit from the smallest enclosing
<b>for</b>,
<b>while</b>
or
<b>until</b>
loop, if any; or from the
<i>n</i>th
enclosing loop if
<i>n</i>
is specified.
The value of
<i>n</i>
is an unsigned decimal integer greater than or equal to 1.
The default is equivalent to <i>n</i><b>=</b>1.
If
<i>n</i>
is greater than the number of enclosing loops,
the last enclosing loop is exited from.
Execution will continue with the command immediately following the loop.
<h5><a name = "tag_001_014_001_003">&nbsp;</a>EXAMPLES</h5>
<pre>
<code>
for i in *
do
    if test -d "$i"
    then break
    fi
done
</code>
</pre>
<h5><a name = "tag_001_014_001_004">&nbsp;</a>EXIT STATUS</h5>
<dl compact>

<dt>0<dd>Successful completion.

<dt>&gt;0<dd>The
<i>n</i>
value was not an unsigned decimal integer greater than or equal to 1.

</dl>
<hr size=2 noshade>
<h4><a name = "tag_001_014_002">&nbsp;</a>colon - Null Utility</h4>
<h5><a name = "tag_001_014_002_001">&nbsp;</a>SYNOPSIS</h5>
<pre><code>

: <b>[</b><i>argument</i> ...<b>]
</b></code>
</pre>
<h5><a name = "tag_001_014_002_002">&nbsp;</a>DESCRIPTION</h5>
This utility will only expand command
<i>argument</i>s.
It is used when a command is needed, as in the
<i>then</i>
condition of an
<b>if</b>
command, but nothing is to be done by the command.
<h5><a name = "tag_001_014_002_003">&nbsp;</a>EXAMPLES</h5>
<pre>
<code>
: ${X=abc}
if     false
then   :
else   echo $X
fi
<b>abc
</b></code>
</pre>
<p>
As with any of the special built-ins, the null utility
can also have variable assignments and redirections
associated with it, such as:
<pre>
<code>
x=y : &gt; z
</code>
</pre>
which sets variable <b>x</b>
to the value y
(so that it persists after the null utility completes)
and creates or truncates file
<b>z</b>.
<h5><a name = "tag_001_014_002_004">&nbsp;</a>EXIT STATUS</h5>
Zero.
<hr size=2 noshade>
<h4><a name = "tag_001_014_003">&nbsp;</a>continue - Continue for, while or until Loop</h4>
<h5><a name = "tag_001_014_003_001">&nbsp;</a>SYNOPSIS</h5>
<code>
<i>continue</i>
<b>[</b><i>n</i><b>]</b>
</code>
<h5><a name = "tag_001_014_003_002">&nbsp;</a>DESCRIPTION</h5>
The
<i>continue</i>
utility will return to the top of the smallest enclosing
<b>for</b>,
<b>while</b>
or
<b>until</b>
loop, or to the top of the
<i>n</i>th
enclosing loop, if
<i>n</i>
is specified.
This involves repeating the condition list of a
<b>while</b>
or
<b>until</b>
loop or performing the next assignment of a
<b>for</b>
loop, and reexecuting the loop if appropriate.
<p>
The value of
<i>n</i>
is a decimal integer greater than or equal to 1.
The default is equivalent to
<i>n</i>=1.
If
<i>n</i>
is greater than the number of enclosing loops,
the last enclosing loop is used.
<h5><a name = "tag_001_014_003_003">&nbsp;</a>EXAMPLES</h5>
<pre>
<code>
for i in *
do
    if test -d "$i"
    then continue
    fi
done
</code>
</pre>
<h5><a name = "tag_001_014_003_004">&nbsp;</a>EXIT STATUS</h5>
<dl compact>

<dt>0<dd>Successful completion.

<dt>&gt;0<dd>The
<i>n</i>
value was not an unsigned decimal integer greater than or equal to 1.

</dl>
<hr size=2 noshade>
<h4><a name = "tag_001_014_004">&nbsp;</a>dot - Execute Commands in Current Environment</h4>
<h5><a name = "tag_001_014_004_001">&nbsp;</a>SYNOPSIS</h5>
<pre><code>

</pre>
. <i>file</i>
</code>
<h5><a name = "tag_001_014_004_002">&nbsp;</a>DESCRIPTION</h5>
The shell will execute commands from the
<i>file</i>
in the current environment.
<p>
If
<i>file</i>
does not contain a slash,
the shell will use the search path specified by
to find the directory containing
<i>file</i>.
Unlike normal command search, however, the file searched
for by the
<i>dot</i>
utility need not be executable.
If no readable file is found,
a non-interactive shell will abort;
an interactive shell will write a diagnostic message to standard error,
but this condition will not be considered a syntax error.
<h5><a name = "tag_001_014_004_003">&nbsp;</a>EXAMPLES</h5>
<pre>
<code>
cat foobar
<b>foo=hello bar=world
</b>. foobar
echo $foo $bar
<b>hello world</b>
</code>
</pre>
<h5><a name = "tag_001_014_004_004">&nbsp;</a>EXIT STATUS</h5>
Returns the value of the last command executed,
or a zero exit status if no command is executed.
<hr size=2 noshade>
<h4><a name = "tag_001_014_005">&nbsp;</a>eval - Construct Command by Concatenating Arguments</h4>
<h5><a name = "tag_001_014_005_001">&nbsp;</a>SYNOPSIS</h5>
<pre><code>

</pre>
<i>eval</i>
<b>[</b><i>argument&nbsp;...</i><b>]</b>
</code>
<h5><a name = "tag_001_014_005_002">&nbsp;</a>DESCRIPTION</h5>
The
<i>eval</i>
utility will construct a command by concatenating
<i>argument</i>s
together, separating each with a
space character.
The constructed command will be read and executed by the shell.
<h5><a name = "tag_001_014_005_003">&nbsp;</a>EXAMPLES</h5>
<pre>
<code>
foo=10 x=foo
y='$'$x
echo $y
<b>$foo
</b>eval y='$'$x
echo $y
<b>10
</b></code>
</pre>
<h5><a name = "tag_001_014_005_004">&nbsp;</a>EXIT STATUS</h5>
If there are no <i>argument</i>s,
or only null arguments,
<i>eval</i>
will return a zero exit status; otherwise,
it will return the exit status of the command defined by the string of
concatenated <i>argument</i>s separated by spaces.
<hr size=2 noshade>
<h4><a name = "tag_001_014_006">&nbsp;</a>exec - Execute Commands and Open, Close or Copy File Descriptors</h4>
<h5><a name = "tag_001_014_006_001">&nbsp;</a>SYNOPSIS</h5>
<pre><code>

exec <b>[</b><i>command </i><b>[</b><i>argument</i> ...<b>]]
</b></code>
</pre>
<h5><a name = "tag_001_014_006_002">&nbsp;</a>DESCRIPTION</h5>
The
<i>exec</i>
utility will open, close or copy file descriptors as specified by
any redirections as part of the command.
<p>
If
<i>exec</i>
is specified without
<i>command</i>
or
<i>arguments,</i>
and any file descriptors with numbers &gt; 2 are opened
with associated redirection statements,
it is unspecified whether those file descriptors
remain open when the shell invokes another utility.
Scripts concerned that child shells could misuse open
file descriptors can always close them explicitly,
as shown in one of the following examples.
<p>
If
<i>exec</i>
is specified with
<i>command</i>,
it will replace the shell with
<i>command</i>
without creating a new process.
If
<i>argument</i>s
are specified, they are arguments to
<i>command</i>.
Redirection will affect the current shell execution environment.
<h5><a name = "tag_001_014_006_003">&nbsp;</a>EXAMPLES</h5>
<p>
Open
<b>readfile</b>
as file descriptor 3 for reading:
<pre>
<code>
exec 3&lt; readfile
</code>
</pre>
<p>
Open
<b>writefile</b>
as file descriptor 4 for writing:
<pre>
<code>
exec 4&gt; writefile
</code>
</pre>
<p>
Make unit 5 a copy of unit 0:
<pre>
<code>
exec 5&lt;&amp;0
</code>
</pre>
<p>
Close file unit 3:
<pre>
<code>
exec 3&lt;&amp;-
</code>
</pre>
<p>
Cat the file
<b>maggie</b>
by replacing the current shell with the
<i><a href="cat.html">cat</a></i>
utility:
<pre>
<code>
exec cat maggie
</code>
</pre>
<h5><a name = "tag_001_014_006_004">&nbsp;</a>EXIT STATUS</h5>
If
<i>command</i>
is specified,
<i>exec</i>
will not return to the shell;
rather, the exit
status of the process will be the exit status of the program implementing
<i>command</i>,
which overlaid the shell.
If
<i>command</i>
is not found, the exit status will be 127.
If
<i>command</i>
is found, but it
is not an executable utility, the exit status will be 126.
If a redirection error occurs (see
<xref href=sherr><a href="#tag_001_008_001">
Consequences of Shell Errors
</a></xref>),
the shell will exit with a value in the range 1-125.
Otherwise,
<i>exec</i>
will return a zero exit status.
<hr size=2 noshade>
<h4><a name = "tag_001_014_007">&nbsp;</a>exit - Cause the Shell to Exit</h4>
<h5><a name = "tag_001_014_007_001">&nbsp;</a>SYNOPSIS</h5>
<pre><code>

</pre>
<i>exit</i>
<b>[</b><i>n</i><b>]</b>
</code>
<h5><a name = "tag_001_014_007_002">&nbsp;</a>DESCRIPTION</h5>
The
<i>exit</i>
utility causes the shell to exit with the exit status specified by
the unsigned decimal integer
<i>n</i>.
If
<i>n</i>
is specified, but its value
is not between 0 and 255 inclusively,
the exit status is undefined.
<p>
As explained in other sections, certain exit status values
have been reserved for special uses and should be used
by applications only for those purposes:
<dl compact>

<dt>126<dd>A command to be executed was found,
but the file was not an executable utility.

<dt>127<dd>A command to be executed was not found.

<dt>&gt;128<dd>A command was interrupted by a signal.

</dl>
<p>
A trap on
<b>EXIT</b>
will be executed before the shell terminates,
except when the
<i>exit</i>
utility is invoked in that trap itself, in which case
the shell will exit immediately.
<h5><a name = "tag_001_014_007_003">&nbsp;</a>EXAMPLES</h5>
<p>
Exit with a
<i>true</i>
value:
<pre>
<code>
exit 0
</code>
</pre>
<p>
Exit with a
<i>false</i>
value:
<pre>
<code>
exit 1
</code>
</pre>
<h5><a name = "tag_001_014_007_004">&nbsp;</a>EXIT STATUS</h5>
The exit status will be
<i>n</i>,
if specified.
Otherwise, the value will be the exit value of the last command executed,
or zero if no command was executed.
When
<i>exit</i>
is executed in a trap action,
the last command is considered to be the command
that executed immediately preceding the trap action.
<hr size=2 noshade>
<h4><a name = "tag_001_014_008">&nbsp;</a>export - Set Export Attribute for Variables</h4>
<h5><a name = "tag_001_014_008_001">&nbsp;</a>SYNOPSIS</h5>
<pre><code>

</pre>
<i>export</i>
<i>name</i><b>[</b>=<i>word</i><b>]</b>...
<br>
<i>export</i>
<b>-p</b>
</code>
<h5><a name = "tag_001_014_008_002">&nbsp;</a>DESCRIPTION</h5>
The shell will give the export attribute
to the variables corresponding to the specified
<i>name</i>s,
which will cause them to be
in the environment of subsequently executed commands.
<p>
The
<i>export</i>
special built-in supports the <b>XBD</b> specification, <a href="../xbd/utilconv.html#usg"><b>Utility Syntax Guidelines</b>&nbsp;</a> .
<p>
When
<b>-p</b>
is specified,
<i>export</i>
will write to the standard output
the names and values of all exported variables,
in the following format:
<pre>
<code>
<tt>"export %s=%s\n"</tt>, &lt;<i>name</i>&gt;,
&lt;<i>value</i>&gt;
</code>
</pre>
<p>
The
<b>-p</b>
option allows portable access to the values
that can be saved and then later restored using, for instance,
a dot script.
<p>
The shell will format the output,
including the proper use of quoting,
so that it is suitable for reinput to the shell as commands
that achieve the same exporting results.
<p>
When no arguments are given,
the results are unspecified.
<h5><a name = "tag_001_014_008_003">&nbsp;</a>EXAMPLES</h5>
<p>
Export
and
variables:
<pre>
<code>
export PWD HOME
</code>
</pre>
<p>
Set and export the
variable:
<pre>
<code>
export PATH=/local/bin:$PATH
</code>
</pre>
<p>
Save and restore all exported variables:
<pre>
<code>
export -p &gt; <i>temp-file</i>
unset <i>a lot of variables</i>
... <i>processing</i>
. <i>temp-file</i>
</code>
</pre>
<h5><a name = "tag_001_014_008_004">&nbsp;</a>EXIT STATUS</h5>
Zero.
<hr size=2 noshade>
<h4><a name = "tag_001_014_009">&nbsp;</a>readonly - Set Read-only Attribute for Variables</h4>
<h5><a name = "tag_001_014_009_001">&nbsp;</a>SYNOPSIS</h5>
<pre><code>

</pre>
<i>readonly</i>
<i>name</i><b>[</b>=<i>word</i><b>]</b>...
<br>
<i>readonly</i>
<b>-p</b>
</code>
<h5><a name = "tag_001_014_009_002">&nbsp;</a>DESCRIPTION</h5>
The variables whose
<i>name</i>s
are specified will be given the
<i>readonly</i>
attribute.
The values of variables with the read-only attribute
cannot be changed by subsequent assignment,
nor can those variables be unset by the
<i>unset</i>
utility.
<p>
Some versions of the shell exist that preserve
the read-only attribute across separate invocations.
This specification allows this behaviour, but does not require it.
<p>
The
<i>readonly</i>
special built-in supports the <b>XBD</b> specification, <a href="../xbd/utilconv.html#usg"><b>Utility Syntax Guidelines</b>&nbsp;</a> .
<p>
When
<b>-p</b>
is specified,
<i>readonly</i>
will write to the standard output
the names and values of all read-only variables,
in the following format:
<pre>
<code>
<tt>"readonly %s=%s\n"</tt>, &lt;<i>name</i>&gt;,
&lt;<i>value</i>&gt;
</code>
</pre>
<p>
The shell will format the output,
including the proper use of quoting,
so that it is suitable for reinput to the shell as commands
that achieve the same attribute-setting results.
<p>
The
<b>-p</b>
option allows portable access to the values
that can be saved and then later restored using, for instance,
a dot script.
(See a related example under
<i><a href="chap2.html#tag_001_014_008">export</a></i>.)
<h5><a name = "tag_001_014_009_003">&nbsp;</a>EXAMPLES</h5>
<pre>
<code>
readonly HOME PWD
</code>
</pre>
<h5><a name = "tag_001_014_009_004">&nbsp;</a>EXIT STATUS</h5>
Zero.
<hr size=2 noshade>
<h4><a name = "tag_001_014_010">&nbsp;</a>return - Return from a Function</h4>
<h5><a name = "tag_001_014_010_001">&nbsp;</a>SYNOPSIS</h5>
<pre><code>

</pre>
<i>return</i>
<b>[</b><i>n</i><b>]</b>
</code>
<h5><a name = "tag_001_014_010_002">&nbsp;</a>DESCRIPTION</h5>
The return utility will cause the shell to stop executing the
current function or dot script.
If the shell is not currently executing a function or dot script,
the results are unspecified.
<p>
The results of returning a number greater than 255 are undefined
because of differing practices in the various historical implementations.
Some shells AND out all but the low-order 8 bits; others allow larger
values, but not of unlimited size.
<p>
See the discussion of appropriate exit status values under
<i><a href="chap2.html#tag_001_014_007">exit</a></i>.
<h5><a name = "tag_001_014_010_003">&nbsp;</a>EXIT STATUS</h5>
The value of the special parameter ? will be set to
<i>n</i>,
an unsigned decimal integer,
or to the exit status of the last command executed if
<i>n</i>
is not specified.
If the value of
<i>n</i>
is greater than 255, the results are undefined.
When
<i>return</i>
is executed in a trap action,
the last command is considered to be the command
that executed immediately preceding the trap action.
<hr size=2 noshade>
<h4><a name = "tag_001_014_011">&nbsp;</a>set - Set or Unset Options and Positional Parameters</h4>
<h5><a name = "tag_001_014_011_001">&nbsp;</a>SYNOPSIS</h5>
<pre><code>

set <b>[</b>-abCefmnuvx<b>][</b>-h<b>][</b>-o&nbsp;<i>option</i><b>][</b><i>argument</i><b>...]</b>
set <b>[</b>+abCefmnuvx<b>][</b>+h<b>][</b>-o&nbsp;<i>option</i><b>][</b><i>argument</i><b>...]</b>
set --<b>[</b><i>argument...</i><b>]</b>
set -<b>[</b><i>argument...</i><b>]</b>
</code>
</pre>
<h5><a name = "tag_001_014_011_002">&nbsp;</a>DESCRIPTION</h5>
If no options or
<i>argument</i>s
are specified,
<i>set</i>
will write the names and values of all shell variables
in the collation sequence of the current locale.
Each
<i>name</i>
will start on a separate line, using the format:
<code>
<p>
<tt>"%s=%s\n"</tt>, &lt;<i>name</i>&gt;,
&lt;<i>value</i>&gt;
</p>
</code>
<p>
The
<i>value</i>
string will be written with appropriate quoting so that it is
suitable for reinput to the shell,
setting or resetting, as far as possible, the variables that are currently set.
Read-only variables cannot be reset.
See the description of shell quoting in
<xref href=quoting><a href="#tag_001_002">
Quoting
</a></xref>.
<p>
When options are specified, they will set or unset attributes
of the shell, as described below.
When
<i>argument</i>s
are specified, they will cause positional parameters to be set or unset,
as described below.
Setting or unsetting attributes and positional parameters are not
necessarily related actions, but they can be combined in a single
invocation of
<i>set</i>.
<p>
The
<i>set</i>
special built-in supports the <b>XBD</b> specification, <a href="../xbd/utilconv.html#usg"><b>Utility Syntax Guidelines</b>&nbsp;</a>  except that
options can be specified with either a leading
hyphen (meaning enable the option) or plus sign (meaning disable it).
<p>
Implementations support the options in the following list
in both their hyphen and plus-sign forms.
These options can also be specified as options to
<i><a href="sh.html">sh</a></i>.
<dl compact>

<dt><b>-a</b>
<dd>When this option is on, the export attribute will be set
for each variable to which an assignment is performed.
(See
<b>Assignment</b>
in the <b>XBD</b> specification, <a href="../xbd/glossary.html"><b>Glossary</b>&nbsp;</a> .)
If the assignment precedes a utility name in a command,
the export attribute will not persist in the current execution
environment after the utility completes,
with the exception that preceding
one of the special built-in utilities will cause the export
attribute to persist after the built-in has completed.
If the assignment does not precede a utility name in
the command,
or if the assignment is a result of the operation of the
<i><a href="getopts.html">getopts</a></i>
or
<i><a href="read.html">read</a></i>
utilities,
the export attribute will persist until the
variable is unset.

<dt><b>-b</b>
<dd>Cause the shell to notify the user asynchronously of
background job completions.
The following message will be written to standard error:
<pre>
<code>
"[%d]%c %s%s\n", <i>&lt;job-number&gt;</i>, <i>&lt;current&gt;</i>, <i>&lt;status&gt;</i>, <i>&lt;job-name&gt;</i>
</code>
</pre>
where the fields are as follows:
<dl compact>

<dt><i>&lt;current&gt;</i><dd>The character "+" identifies the job that would be used as a
default for the
<i><a href="fg.html">fg</a></i>
or
<i><a href="bg.html">bg</a></i>
utilities; this job can also be specified using the
<i>job_id</i>
<b>%+</b>
or
<b>%%</b>.
The character "-" identifies the job that would become the default
if the current default job were to exit;
this job can also be specified using the
<i>job_id</i>
<b>%-</b>.
For other jobs, this field is a space character.
At most one job can be identified with
"+" and at most one job can be identified with "-".
If there is any suspended job, then the current job
will be a suspended job.
If there are at least two suspended jobs,
then the previous job will also be a suspended job.

<dt><i>&lt;job-number&gt;</i><dd>A number that can be used to identify the process group
to the
<i><a href="wait.html">wait</a></i>,
<i><a href="fg.html">fg</a></i>,
<i><a href="bg.html">bg</a></i>
and
<i><a href="kill.html">kill</a></i>
utilities.
Using these utilities, the job can be identified
by prefixing the job number with "%".

<dt><i>&lt;status&gt;</i><dd>Unspecified.

<dt><i>&lt;job-name&gt;</i><dd>Unspecified.

</dl>
<p>
When the shell notifies the user a job has been completed,
it may remove the job's process ID
from the list of those known in the current shell execution environment;
see
<xref href=asyncl><a href="#tag_001_009_003">
Lists
</a></xref>.
Asynchronous notification will not be enabled by default.
<br>
<dt><b>-C</b>
<dd>(Upper-case C.)
Prevent existing files from being overwritten by the shell's
"&gt;"
redirection operator (see
<xref href=rediro><a href="#tag_001_007_002">
Redirecting Output
</a></xref>);
the
&gt;|
redirection operator will override this
<i>noclobber</i>
option for an individual file.
<br>
<dt><b>-e</b>
<dd>When this option is on, if a simple command
fails for any of the reasons listed in
<xref href=sherr><a href="#tag_001_008_001">
Consequences of Shell Errors
</a></xref>
or returns an exit status value &gt;0,
and is not part of the compound list following a
<b>while</b>,
<b>until</b>
or
<b>if</b>
keyword,
and is not a part of an AND or OR list,
and is not a pipeline preceded by the
"!"
reserved word,
then the shell will immediately exit.
<br>
<dt><b>-f</b>
<dd>The shell will disable pathname expansion.
<p>
<dt><b>-h</b><dd>Locate and remember utilities invoked by functions as
those functions are defined
(the utilities are normally located when the function is executed).
<br>
<dt><b>-m</b>
<dd>All jobs are run in their own process groups.
Immediately before the shell issues a prompt after
completion of the background job, a message reporting
the exit status of the background job will be written to standard error.
If a foreground job stops, the shell will write a message
to standard error to that effect,
formatted as described by the
<i><a href="jobs.html">jobs</a></i>
utility.
In addition, if a job changes status other than
exiting (for example, if it stops for input or output or is
stopped by a SIGSTOP signal), the shell will write a similar message
immediately prior to writing the next prompt.
This option is enabled
by default for interactive shells.
<br>
<dt><b>-n</b>
<dd>The shell will read commands but not execute them; this
can be used to check for shell script syntax errors.
An interactive shell may ignore this option.
<br>
<dt><b>-o&nbsp;</b><i>option</i>
<dd>
Set various options, many of which are equivalent to the
single option letters.
The following values of
<i>option</i>
are supported:
<dl compact>

<dt><b>allexport</b><dd>Equivalent to
<b>-a</b>.

<dt><b>errexit</b><dd>Equivalent to
<b>-e</b>.

<dt><b>ignoreeof</b><dd>Prevent an interactive shell from exiting on end-of-file.
This setting prevents accidental logouts when
control-D
is entered.
A user must explicitly
<i><a href="#tag_001_014_007">exit</a></i>
to leave the interactive shell.

<dt><b>monitor</b><dd>Equivalent to
<b>-m</b>.

<dt><b>noclobber</b><dd>Equivalent to
<b>-C</b>
(upper-case C).

<dt><b>noglob</b><dd>Equivalent to
<b>-f</b>.

<dt><b>noexec</b><dd>Equivalent to
<b>-n</b>.

<dt><b>nolog</b><dd>Prevent the entry of function definitions into the command history.
See
<xref href=shcmdhist><a href="sh.html#tag_001_014_2004_001">
Command History List
</a></xref>.

<dt><b>notify</b><dd>Equivalent to
<b>-b</b>.

<dt><b>nounset</b><dd>Equivalent to
<b>-u</b>.

<dt><b>verbose</b><dd>Equivalent to
<b>-v</b>.

<dt><b>vi</b><dd>Allow shell command-line editing using the built-in
<i><a href="vi.html">vi</a></i>
editor.
Enabling
<b>vi</b>
mode disables
any other command-line editing mode
provided as an implementation extension.

It need not be possible to set
<b>vi</b>
mode on for certain block-mode terminals.

<dt><b>xtrace</b><dd>Equivalent to
<b>-x</b>.

</dl>
<p>
<br>
<dt><b>-u</b>
<dd>The shell will write a message to standard error when it tries to expand
a variable that is
not set
and immediately exit.
An interactive shell will not exit.
<br>
<dt><b>-v</b>
<dd>The shell will write
its input to standard error as it is read.
<br>
<dt><b>-x</b>
<dd>The shell will write to standard error a trace for each command
after it expands the command and before it executes it.
<p>
</dl>
<p>
The default for all these options is off (unset) unless the
shell was invoked with them on (see
<i><a href="sh.html">sh</a></i>).
All the positional parameters will be unset
before any new values are assigned.
<p>
The remaining arguments will be
assigned in order to the positional parameters.
The special parameter
"#"
will be set to reflect the number of
positional parameters.
<p>
The special argument
--
immediately following the
<i>set</i>
command name can be used to delimit the arguments
if the first argument begins with "+" or "-",
or to prevent inadvertent
listing of all shell variables when there are no arguments.
The command
<i>set</i>
-- without
<i>argument</i>
will unset all positional parameters and set the special parameter
"#" to zero.
<p>
In the obsolescent version, the
<i>set</i>
command name followed by "-" with no other arguments will turn off the
<b>-v</b>
and
<b>-x</b>
options without changing the positional parameters.
The
<i>set</i>
command name followed by "-" with other arguments will turn off the
<b>-v</b>
and
<b>-x</b>
options and assign the arguments to the positional parameters in order.
<h5><a name = "tag_001_014_011_003">&nbsp;</a>EXAMPLES</h5>
Write out all variables and their values:
<pre>
<code>
set
</code>
</pre>
Set
$1,
$2
and
$3
and set
$#
to 3:
<pre>
<code>
set c a b
</code>
</pre>
<p>
Turn on the
<b>-x</b>
and
<b>-v</b>
options:
<pre>
<code>
set -xv
</code>
</pre>
<br>
<p>
Unset all positional parameters:
<pre>
<code>
set -&nbsp;-
</code>
</pre>
<p>
Set
$1
to the value of
<b>x</b>,
even if
<b>x</b>
begins with - or +:
<pre>
<code>
set -&nbsp;- "$x"
</code>
</pre>
<p>
Set the positional parameters to the expansion of
<b>x</b>,
even if
<b>x</b>
expands with a leading - or +:
<pre>
<code>
set -&nbsp;- $x
</code>
</pre>
<h5><a name = "tag_001_014_011_004">&nbsp;</a>EXIT STATUS</h5>
Zero.
<hr size=2 noshade>
<h4><a name = "tag_001_014_012">&nbsp;</a>shift - Shift Positional Parameters</h4>
<h5><a name = "tag_001_014_012_001">&nbsp;</a>SYNOPSIS</h5>
<pre><code>

</pre>
<i>shift</i>
<b>[</b><i>n</i><b>]</b>
</code>
<h5><a name = "tag_001_014_012_002">&nbsp;</a>DESCRIPTION</h5>
The positional parameters will be shifted.
Positional parameter 1 will be assigned the value of parameter
(1+<i>n</i>),
parameter 2 will be assigned the value of parameter
(2+<i>n</i>),
and so on.
The parameters represented by the numbers
$#
down to
$#-<i>n</i>+1
will be unset, and the parameter "#" will be updated to reflect the new
number of positional parameters.
<p>
The value
<i>n</i>
will be an unsigned decimal integer
less than or equal to the value of the special parameter "#".
If
<i>n</i>
is not given, it will be assumed to be
1.
If
<i>n</i>
is
0,
the positional and special parameters will not be changed.
<h5><a name = "tag_001_014_012_003">&nbsp;</a>EXAMPLES</h5>
<pre>
<code>
<b>$</b> set a b c d e
<b>$</b> shift 2
<b>$</b> echo $*
<b>c d e
</b></code>
</pre>
<h5><a name = "tag_001_014_012_004">&nbsp;</a>EXIT STATUS</h5>
The exit status will be &gt;0 if
<i>n</i>&gt;$#;
otherwise, it will be zero.
<hr size=2 noshade>
<h4><a name = "tag_001_014_013">&nbsp;</a>times - Write Process Times</h4>
<h5><a name = "tag_001_014_013_001">&nbsp;</a>SYNOPSIS</h5>
<pre><code>

</pre>
<i>times</i>
</code>
<h5><a name = "tag_001_014_013_002">&nbsp;</a>DESCRIPTION</h5>
Write the accumulated user and system times for the
shell and for all of its child processes, in the following
POSIX locale format:
<code>
<p>
<tt>"%dm%fs %dm%fs\n%dm%fs %dm%fs\n"</tt>, &lt;<i>shell&nbsp;user&nbsp;minutes</i>&gt;,
&lt;<i>shell&nbsp;user&nbsp;seconds</i>&gt;,
&lt;<i>shell&nbsp;system&nbsp;minutes</i>&gt;,
&lt;<i>shell&nbsp;system&nbsp;seconds</i>&gt;,
&lt;<i>children&nbsp;user&nbsp;minutes</i>&gt;,
&lt;<i>children&nbsp;user&nbsp;seconds</i>&gt;,
&lt;<i>children&nbsp;system&nbsp;minutes</i>&gt;
&lt;<i>children&nbsp;system&nbsp;seconds</i>&gt;
</p>
</code>
<p>
The four pairs of times correspond to the members of the <b>XSH</b> specification
<i><a href="../xsh/systimes.h.html">&lt;sys/times.h&gt;</a></i>
<b>tms</b>
structure as returned by
<i><a href="../xsh/times.html">times()</a></i>:
<i>tms_utime</i>,
<i>tms_stime</i>,
<i>tms_cutime</i>
and
<i>tms_cstime</i>,
respectively.
<h5><a name = "tag_001_014_013_003">&nbsp;</a>EXAMPLES</h5>
<pre>
<code>
<b>$</b> times
<b>0m0.43s 0m1.11s
8m44.18s 1m43.23s
</b></code>
</pre>
<h5><a name = "tag_001_014_013_004">&nbsp;</a>EXIT STATUS</h5>
Zero.
<hr size=2 noshade>
<h4><a name = "tag_001_014_014">&nbsp;</a>trap - Trap Signals</h4>
<h5><a name = "tag_001_014_014_001">&nbsp;</a>SYNOPSIS</h5>
<pre><code>

</pre>
<i>trap</i>
<b>[</b><i>action&nbsp;&nbsp;condition&nbsp;...</i><b>]</b>
</code>
<h5><a name = "tag_001_014_014_002">&nbsp;</a>DESCRIPTION</h5>
If
<i>action</i>
is "-", the shell will reset each
<i>condition</i>
to the default value.
If
<i>action</i>
is null
(&quot;),
the shell will ignore each specified
<i>condition</i>
if it arises.
Otherwise, the argument
<i>action</i>
will be read and executed by the shell when one of the corresponding
conditions arises.
The action of the trap will override a previous action
(either default action or one explicitly set).
The value of
$?
after the trap action completes will be the value it
had before the trap was invoked.
<p>
The condition can be EXIT, 0 (equivalent to EXIT)
or a signal specified using a symbolic name, without the SIG
prefix, as listed in the tables of signal names in the <b>XSH</b> specification under
<i><a href="../xsh/signal.h.html">&lt;signal.h&gt;</a></i>;
for example, HUP, INT, QUIT, TERM.
Implementations may permit lower-case signal names
or names with the SIG prefix as an extension.
Setting a trap for SIGKILL or SIGSTOP produces undefined results.
<p>
The environment in which the shell executes a trap on
<b>EXIT</b>
will be identical to the environment immediately
after the last command executed before the trap on
<b>EXIT</b>
was taken.
<p>
Each time the trap is invoked, the
<i>action</i>
argument will be processed in a manner equivalent to:
<pre>
<code>
eval "$action"
</code>
</pre>
<p>
Signals that were ignored on
entry to a non-interactive shell cannot be trapped or reset, although
no error need be reported when attempting to do so.
An interactive shell may reset or catch signals ignored on entry.
Traps will remain in place for a given
shell until explicitly changed with another
<i>trap</i>
command.
<p>
When a subshell is entered, traps that are not being ignored are set to
the default actions.
This does not imply that the
<i>trap</i>
command cannot be used within the subshell
to set new traps.
<p>
The
<i>trap</i>
command with no arguments will write to standard output a list of
commands associated with each condition.
The format is:
<code>
<p>
<tt>"trap -&nbsp;- %s %s ...\n"</tt>, &lt;<i>action</i>&gt;,
&lt;<i>condition</i>&gt;
</p>
</code>
<p>
The shell will format the output,
including the proper use of quoting,
so that it is suitable for reinput to the shell as commands
that achieve the same trapping results.
For example:
<pre>
<code>
save_traps=$(trap)
...
eval "$save_traps"
</code>
</pre>
<p>
XSI-conformant systems also allow numeric signal numbers for
the conditions, corresponding to the following signal names:
<pre>
<table  bordercolor=#000000 border=1 align=center><tr valign=top><th align=center><b>Signal Number</b>
<th align=center><b>Signal Name</b>
<tr valign=top><td align=center>1
<td align=left>SIGHUP
<tr valign=top><td align=center>2
<td align=left>SIGINT
<tr valign=top><td align=center>3
<td align=left>SIGQUIT
<tr valign=top><td align=center>6
<td align=left>SIGABRT
<tr valign=top><td align=center>9
<td align=left>SIGKILL
<tr valign=top><td align=center>14
<td align=left>SIGALRM
<tr valign=top><td align=center>15
<td align=left>SIGTERM
</table>
</pre>
<p>
The
<i>trap</i>
special built-in supports the <b>XBD</b> specification, <a href="../xbd/utilconv.html#usg"><b>Utility Syntax Guidelines</b>&nbsp;</a> .
<h5><a name = "tag_001_014_014_003">&nbsp;</a>EXAMPLES</h5>
Write out a list of all traps and actions:
<pre>
<code>
trap
</code>
</pre>
<p>
Set a trap so the
<i>logout</i>
utility in the
directory will execute when the shell terminates:
<pre>
<code>
trap '$HOME/logout' EXIT
</code>
</pre>
<p>
or:
<pre>
<code>
trap '$HOME/logout' 0
</code>
</pre>
<p>
Unset traps on INT, QUIT, TERM and EXIT:
<pre>
<code>
trap - INT QUIT TERM EXIT
</code>
</pre>
<h5><a name = "tag_001_014_014_004">&nbsp;</a>EXIT STATUS</h5>
If the trap name or number is invalid, a non-zero exit status
will be returned; otherwise, zero will be returned.
For both interactive and non-interactive shells,
invalid signal names or numbers will not be considered a syntax error
and will not cause the shell to abort.
<hr size=2 noshade>
<h4><a name = "tag_001_014_015">&nbsp;</a>unset - Unset Values and Attributes of Variables and Functions</h4>
<h5><a name = "tag_001_014_015_001">&nbsp;</a>SYNOPSIS</h5>
<pre><code>

</pre>
<i>unset</i>
<b>[-fv]</b>
<i>name&nbsp;...</i>
</code>
<h5><a name = "tag_001_014_015_002">&nbsp;</a>DESCRIPTION</h5>
Each variable or function specified by
<i>name</i>
will be unset.
<p>
If
<b>-v</b>
is specified,
<i>name</i>
refers to a variable name and the shell will unset it and remove
it from the environment.
Read-only variables cannot be unset.
<p>
If
<b>-f</b>
is specified,
<i>name</i>
refers to a function and the shell will unset the function definition.
<p>
If neither
<b>-f</b>
nor
<b>-v</b>
is specified,
<i>name</i>
refers to a variable; if a variable by that name does not exist,
it is unspecified whether a function
by that name, if any, will be unset.
<p>
Unsetting a variable or function that was not
previously set is not considered
an error and will not cause the shell to abort.
<p>
The
<i>unset</i>
special built-in supports the <b>XBD</b> specification, <a href="../xbd/utilconv.html#usg"><b>Utility Syntax Guidelines</b>&nbsp;</a> .
<p>
Note that:
<pre>
<code>
VARIABLE=
</code>
</pre>
is not equivalent to an
<i>unset</i>
of
<b>VARIABLE</b>;
in the example,
<b>VARIABLE</b>
is set to
"".
Also, the variables that can be
<i>unset</i>
should not be misinterpreted to include the special parameters (see
<xref href=specpar><a href="#tag_001_005_002">
Special Parameters
</a></xref>).
<h5><a name = "tag_001_014_015_003">&nbsp;</a>EXAMPLES</h5>
Unset
variable:
<pre>
<code>
unset -v VISUAL
</code>
</pre>
<p>
Unset the functions
<b>foo</b>
and
<b>bar</b>:
<pre>
<code>
unset -f foo bar
</code>
</pre>
<h5><a name = "tag_001_014_015_004">&nbsp;</a>EXIT STATUS</h5>
<dl compact>

<dt>0<dd>All cases of
<i>name</i>
were successfully unset.

<dt>&gt;0<dd>At least one
<i>name</i>
could not be unset.

</dl>
</blockquote><hr size=2 noshade>
<center><font size=2>
UNIX &reg; is a registered Trademark of The Open Group.<br>
Copyright &copy; 1997 The Open Group
<br> [ <a href="../index.html">Main Index</a> | <a href="../xshix.html">XSH</a> | <a href="../xcuix.html">XCU</a> | <a href="../xbdix.html">XBD</a> | <a href="../cursesix.html">XCURSES</a> | <a href="../xnsix.html">XNS</a> ]

</font></center><hr size=2 noshade>
</body></html>
